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

标签 javascript arrays if-statement

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

相关文章:

php 如果表存在则删除 mysql

python - 将 24 小时添加到 python 中的负时差

javascript - 控制 HTML 中的复选框

javascript - AJAX 搜索系统中的空格不起作用

javascript - contenteditable,在文本末尾设置插入符(跨浏览器)

c - 通过过度分配内存在结构中内联可变长度数组是否有效?

php - 将标准对象数组从 SOAP 循环到数据库 PHP

javascript - 将对象键和值转换为对象数组

c - 难以理解循环

javascript - Google Earth API - 转换 ED50/WGS84