如何将if语句的结果放入我可以稍后返回的新数组中

How to place the results of an if statement into a new array which I can return later

本文关键字:新数组 返回 数组 我可以 if 语句 结果      更新时间:2023-09-26

我对代码相当陌生,我被一个特定的问题困了很长一段时间。我觉得我已经很好地掌握了问题所需要的东西,但是我无法弄清楚如何将if语句的结果返回到一个新的数组中,然后我可以返回。如有任何帮助或建议,我将不胜感激。

function loveTheThrees (myArray) {
var myTotal = 0;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] % 3 === 0) {
    myTotal += myArray[i];
    /* What I'm looking to do at this stage of the problem is place the results into a new array which will be returned rather than myTotal */
}
}
return myTotal; // Placed this here just to test to see if the problem would post the results
}
loveTheThrees ([1, 3, 5, 12, 21]);

您可以使用Array#filter

function loveTheThrees(myArray) {
    return myArray.filter(function (a) {
        return a % 3 === 0;
    });
}
console.log(loveTheThrees([1, 3, 5, 12, 21]));

试试这个:

function loveTheThrees (myArray) {
var newarray = []
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] % 3 === 0) {
    newarray[newarray.length] = myArray[i]
}
}
return newarray;
}
loveTheThrees ([1, 3, 5, 12, 21]);

这样回答你的问题了吗?它取除3(%3)后没有余数的任何项,并将其放入数组newarray中,并返回它。

带箭头函数表达式:

var loveTheThrees = (myArray) => myArray.filter(element => element % 3 === 0);
console.log(loveTheThrees([1, 3, 5, 12, 21]));
相关文章: