循环中调用数组的索引导致错误
所以我基本上导入一个JSON文件。我找回很多数组,每个数组中有4个元素。我想将每个数组中的第3个元素解析为它自己的变量数组。循环中调用数组的索引导致错误
$("#nextQ").click(function() {
var Quotes = [];
var totalQ //The total number of available quotes to choose from
//Get quotes from JSON file
$.ajax({
url: '../facts.json',
datatype: 'json',
type: 'get',
success: function(data) {
console.log(data[0][2]); //This WORKS
console.log(data.length); //Returns 64
totalQ = data.length;
for (i = 0; i <= totalQ; i++) {
Quotes[i] = data[3][2]; //This WORKS
Quotes[i] = data[i][2]; //This gives ERROR
}
}
});
});
当我使用data[i][2]
我得到这个错误:Uncaught TypeError: Cannot read property '2' of undefined
。但是,如果我使用data[6][2]
或任何其他数字,则不会发生此错误。
您需要更新for
循环条件从i <= totalQ;
到i <totalQ;
,因为指数从0
for (i = 0; i < totalQ; i++) {
Quotes[i] = data[i][2];
}
启动或者你可以使用$.each()
为@adeneo建议
$.each(data,function(i,v){
Quotes[i] = v[2];
})
或者您可以使用本机javascript map()
Quotes = data.map(function(v){
return v[2];
})
谢谢你,这个工作。如果错误没有告诉我问题是第二个索引(随机? ?) – Badrush
@Badrush,'data [data.length]'将是未定义的,您试图获取undefined'的属性 –
'我
谢谢,任何想法为什么这会给我一个错误的第二个索引,而不是第64个? – Badrush
或更多jQuery'ish - >'$ .each(data,function(){...' – adeneo