所以我基本上导入了一个 JSON 文件。我找回了很多数组,每个数组都有 4 个元素。我想将每个数组的第三个元素解析到它自己的变量数组中。
$("#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];
})
或者您可以使用 native javascript map()
Quotes = data.map(function(v){
return v[2];
})
关于javascript - 在循环中调用数组的索引导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35810530/