如何使用javascript在新数组中存储可整数
我试图将可被3整除的数字存储在3数组中。这是怎么做到的如何使用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
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
请参见