我正在尝试将2个值添加到我从html页面中提取的数组中。但是,key [0]的值总是返回 undefined ,而在这种情况下我期望为4.
<script type="text/javascript">
$(document).ready(function ()
{
var arrayList = $("some class");
var x = new Array();
var j = 0;
var k = 1;
$.each(arrayList, function(i,e) {
var MyIf = $(e).text();
x[j] = new Array();
if(k == 2) {
x[j][0] = 4; // This always returns undefined, no matter which value I assign.
}
if(k == 3) {
x[j][1] = parseInt(MyIf);
}
if(k % 3 == 0) {
j++;
k = 1;
} else {
k++;
}
});
console.log(x); // the console returns for all [0] "undefined"
});
</script>
我错过了什么?
答案 0 :(得分:4)
这是因为您每次都在each
创建一个新数组。
x[j] = new Array();
因此它始终未定义。
把它放在这里:
if(k % 3 == 0) {
j++;
k = 1;
x[j] = new Array();
}
并且在第一次运行之前忘记给x[j] = new Array();
打电话。
答案 1 :(得分:0)
应该这样做:
var arrayList = [1,2,3,4,5];
var x = new Array();
var j = 0;
var k = 1;
x[j] = new Array();
$.each(arrayList, function(i,e) {
var MyIf = $(e).text();
if(k == 2) {
x[j][0] = 4; // This always returns undefined, no matter which value I assign.
}
if(k == 3) {
x[j][1] = parseInt(MyIf);
}
if(k % 3 == 0) {
j++;
x[j] = new Array();
k = 1;
} else {
k++;
}
});
console.log(x);
在你的代码中,当k变量等于3时,你会覆盖前一个值:
x[j] = new Array();
if(k == 2) {
x[j][0] = 4; // This always returns undefined, no matter which value I assign.
}