我正在尝试迭代变量pieces
,但不知何故它没有触发。在下面的函数中,pieces.length
变为4,但piecesNew
变为[]
- 而且console.log(i)
永远不会到达。
发生了什么事?
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i; i <= pieces.length; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};
答案 0 :(得分:7)
undefined
不是小于或大于任何数字。
var i; // undefined
i < 10; // false
i > 10; // false
您只需确保i
等于0
。
您还希望i
永远不等于pieces.length
,因此请使用<
代替<=
(数组的最后一个索引始终为length - 1
,例如,长度为3的数组具有索引0,1和2 - 第一个索引始终为0,而不是1)
所以:
for (var i = 0; i < pieces.length; i++) {
...
答案 1 :(得分:3)
定义变量i的值var i = 0
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i = 0; i <= pieces.length; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};
答案 2 :(得分:2)
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i = 0; i <= pieces.length; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};
答案 3 :(得分:2)
变化:
for (var i; i <= pieces.length; i++)
要:
for (var i = 0; i < pieces.length; i++)
答案 4 :(得分:1)
最初初始化var i = 0然后它将起作用
self.reworkPieces = function(pieces) {
var piecesNew = [];
console.log(pieces.length)
for (var i = 0; i <= pieces.length - 1; i++) {
console.log(i)
piecesNew[i] = {
c: pieces[i].r,
r: pieces[i].c,
p: i
}
}
console.log(piecesNew)
return piecesNew;
};