Javascript 循环数组以查找可被 3 整除的数字

标签 javascript arrays loops for-loop

我需要找到让 javascript 循环遍历数组的正确方法,找到所有可被 3 整除的数字,并将这些数字放入新数组中。

这是我目前所拥有的..

var array = [],
    threes = [];

function loveTheThrees(array) {
    for (i = 0, len = array.length; i < len; i++) {
    threes = array.push(i % 3);
  }
  return threes;
}

因此,如果我们通过函数传递 [1, 2, 3, 4, 5, 6] 数组,它会将数字 3 和 6 推出“三元组”数组。希望这是有道理的。

最佳答案

您可以使用 Array#filter为了这个任务。

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value or a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

function loveTheThrees(array) {
    return array.filter(function (a) {
        return !(a % 3);
    });
}
document.write('<pre>' + JSON.stringify(loveTheThrees([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 0, 4) + '</pre>');

关于Javascript 循环数组以查找可被 3 整除的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36317125/

相关文章:

arrays - 如何检查数组中的所有值是否都是相同的 mongodb 聚合?

python - 使用循环从列表中查找所有唯一的单词

c++ - 一个单独的循环减慢了一个独立的早期循环?

javascript - 如何检测由贝塞尔曲线制成的物体与圆之间的碰撞?

javascript - 如何从对象中的数组迭代输出数据

javascript - 为什么我们在 `Number.prototype.valueOf` 函数内部使用 `map()`

java - 用作垃圾收集的同步锁的对象数组

c++ - while循环在C++中不循环

javascript - HTML5 将外部内容加载到 div 中并使用pushState()?

javascript - 如何使用 Twig 中实体的现有数据预先填充集合原型(prototype)?