本文介绍了Javascript循环一个数组来查找可以被3整除的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找到正确的方式来通过一个数组的JavaScript循环,找到可以被3整除的所有数字,并将这些数字推入一个新的数组。这是我到目前为止。
$ bfunction 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>);
I am needing to find the correct way to have javascript loop through an array, find all numbers that are divisible by 3, and push those numbers into a new array.
Here is what I have so far..
var array = [], threes = []; function loveTheThrees(array) { for (i = 0, len = array.length; i < len; i++) { threes = array.push(i % 3); } return threes; }So if we pass through an array of [1, 2, 3, 4, 5, 6] through the function, it would push out the numbers 3 and 6 into the "threes" array. Hopefully this makes sense.
解决方案You can use Array#filter for this task.
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整除的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!