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

rth*_*s62 1 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;
}
Run Code Online (Sandbox Code Playgroud)

因此,如果我们通过函数传递[1,2,3,4,5,6]的数组,它会将数字3和6推出到"threes"数组中.希望这是有道理的.

Nin*_*olz 5

您可以使用Array#filter此任务.

filter()callback为数组中的每个元素调用一次提供的函数,并构造一个包含所有值的新数组,该数组callback返回一个true值或一个强制的值true.callback仅对已分配值的数组的索引调用; 对于已删除的索引或从未分配过值的索引,不会调用它.不通过callback测试的数组元素只是被跳过,并且不包含在新数组中.

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>');
Run Code Online (Sandbox Code Playgroud)