更大,我需要console.log
每一个数字,从该行获取数大于n
[ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6]
我知道它应该是这样的
var row = [ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6];
for (var i = 0; i<row; i++)
{
console.log(niz[i]);
}
更大,我需要console.log
每一个数字,从该行获取数大于n
[ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6]
我知道它应该是这样的
var row = [ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6];
for (var i = 0; i<row; i++)
{
console.log(niz[i]);
}
那么你既可以大于10使用for
循环或映射。 For循环会是这样:
for (var i = 0; i<row.length; i++)
{
if (row[i] > 10)
console.log(row[i]);
}
要使用映射:当你在问题中陈述
row.map(function(element){
if (element > 10)
console.log(element);
});
,你需要使用一个for
-loop迭代槽的阵列中的所有项目。这几乎可以正确完成,但是不需要执行i<row
,您需要检查row
(row.length
)的长度。
在你的情况,i
会在你的列表中的索引,直到你达到项目的行数将与一个(i++
)增加在for
-loop每次迭代。
说你缺少的东西是一个if
语句来检查,如果数组中的项目大于10
我试图解释与评论的每一行。
var row = [10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6];
var items = row.length; // number of items in your array
for (var i = 0; i < items; i++) { // iterate trough all the items
var numberInRow = row[i]; // the number with index number i in rows
var isGreaterThanTen = numberInRow > 10; // true if the number is greater than ten
if (isGreaterThanTen) { // will execute if isGreaterThanTen is true
console.log(numberInRow); // print number greater than 10 to console.
}
}
一个forEach
-loop似乎解决你的问题的一个很好的方式:
var row = [ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6];
row.forEach(function(x){if(x>10){console.log(x)}})
,甚至更短的
[10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6].forEach(function(x){if(x>10){console.log(x)}})
输出在两种情况下:
11
12
156
61
89
如果你实际上并不需要记录它们,但要将它们作为数组使用,请使用'filter'代替:'row.filter(function(a){return a> 10;});'。 – Xufox