Javascript循环一个数组来查找可以被3整除的数字 [英] Javascript loop an array to find numbers divisible by 3

查看:688
本文介绍了Javascript循环一个数组来查找可以被3整除的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到正确的方式来通过一个数组的JavaScript循环,找到可以被3整除的所有数字,并将这些数字推入一个新的数组。这是我到目前为止。

  var array = [],
threes = [];

函数loveTheThrees(array){
for(i = 0,len = array.length; i threes = array.push(i% 3);
}
返回三位;





$ b所以如果我们通过一个[1,2,3,4 ,5,6]通过该函数,将数字3和6推出到三阵列。希望这是有道理的。

解决方案

您可以使用
$ b


filter()调用一个提供的 callback 为数组中的每个元素执行一次函数,并为 callback 返回一个真正的值或一个强制为 true 的值。 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>);  


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.

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整除的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆