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