Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/422.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用javascript在新数组中存储可整数_Javascript - Fatal编程技术网

如何使用javascript在新数组中存储可整数

如何使用javascript在新数组中存储可整数,javascript,Javascript,我试图将可被3整除的数字存储在3数组中。这是怎么做到的 var numbers = [1,2,3,4,5,6,7,8,9]; var threes = []; var iLoveThree = function(numbers,threes){ for(i in numbers){ if(i.value % 3 == 0){ threes.push([i]); console.log(threes); } } return

我试图将可被3整除的数字存储在3数组中。这是怎么做到的

var numbers = [1,2,3,4,5,6,7,8,9];
var threes = [];
var iLoveThree = function(numbers,threes){
    for(i in numbers){
      if(i.value % 3 == 0){
        threes.push([i]);
        console.log(threes);
      } 
    } return threes
};
iLoveThree();

有一些问题

  • 您需要使用索引
    numbers[i]
    访问数组中的数字,而不仅仅是检查索引

  • 您还需要将这两个参数传递给
    iLoveThree
    函数

以下是工作代码:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var threes = [];
var iLoveThree = function (numbers, threes) {
    for (i in numbers) {
        if (numbers[i] % 3 === 0) {
            threes.push(numbers[i]);
        }
    }
    return threes;
};

console.log(iLoveThree(numbers, threes));
// [3, 6, 9]
作为补充说明,您可以通过使用简化代码

如果布尔值
num%3===0
为真,则不会从数组中删除该数字

var numbers = [1,2,3,4,5,6,7,8,9].filter(function (num) {
  return num % 3 === 0;
});

console.log(numbers);
// [3, 6, 9]

你推的时候在
i
周围放上括号。您不需要括号

var numbers = [1,2,3,4,5,6,7,8,9];
var threes = [];
var iLoveThree = function(numbers,threes){
    for(i in numbers){
      if(i.value % 3 == 0){
        threes.push(i);   //don't put brackets here
        console.log(threes);
      } 
    } return threes
};
给你:

var numbers = [1,2,3,4,5,6,7,8,9];
function iLoveThree(numbers) {
  return numbers.filter(function(n) {
    return n % 3 === 0;
  });
}
var threes = iLoveThree(numbers);

尝试用
替换
循环
替换
循环中的;使用数组中的编号而不是当前迭代中数组中项目的索引

var数字=[1,2,3,4,5,6,7,8,9];
var threes=[];
对于(变量i=0;i
请参见