gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:06:53 25 4
gpt4 key购买 nike

我对编码还很陌生,而且我已经在某个特定问题上停留了很长一段时间。我觉得我很清楚这个问题需要什么,但是我一辈子都想不出如何将 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]));

关于javascript - 如何将 if 语句的结果放入我稍后可以返回的新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38174316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com