我需要找到让 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 providedcallback
function once for each element in an array, and constructs a new array of all the values for whichcallback
returns a true value or a value that coerces totrue
.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 thecallback
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/