用JS刷LeetCode,刷到第六题ZigZag Conversion报错TypeError: Cannot read property 'push' of undefined
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function(s, numRows) {
var rowArray = new Array(numRows),
dir = true,
n = 1,
i = 0,
temp = 0,
rowArrayCount = 0,
ans = "",
len = s.length;
for (i = 0; i < numRows; i++) {
rowArray[i] = new Array();
}
while (i<len) {
console.log(rowArray);
console.log(rowArray instanceof Array);
console.log(rowArray[rowArrayCount] instanceof Array);
while(dir) {
rowArray[rowArrayCount].push(s.charAt(i));
rowArrayCount++;
i++;
if (i === numRows*n -1) {
dir = false;
n++;
rowArrayCount = numRows-1;
}
}
while(!dir) {
rowArray[rowArrayCount].push(s.charAt(i));
rowArrayCount--;
i++;
if (i === numRows*n -1) {
dir = true;
n++;
rowArrayCount = 0;
}
}
}
for (i = 0; i < numRows; i++) {
temp = rowArray[i].join("");
ans += temp;
}
return ans;
};
其中
console.log(rowArray);
console.log(rowArray instanceof Array);
console.log(rowArray[rowArrayCount] instanceof Array);
输出为:
为什么rowArray[rowArrayCount]是数组却不能使用push方法?
已解决,确实是数组越界,导致
rowArray
没有rowArray[rowArrayCount]
项,所以为undefined
。不过问题书出在i上,忽略了用for循环创建二维数组时临时变量i在for循环结束后作用域问题,此时i的值是for循环结束时的值。应该把i重新设置为0。正确的代码: