[英]Access array variables outside for loop javascript
i am trying to populate a table using datatables jquery library , the problem encountered is that only the last value is displayed ,the values are accessed by looping through data stored in json . 我试图使用datatables jquery库填充表,遇到的问题是只显示最后一个值,通过循环存储在json中的数据来访问这些值。 Here is my code :-
这是我的代码: -
for (var i = 0; i < json_parsed.Users.length; i++) {
var user = json_parsed.Users[i];
if (user.position == "GK") {
goalkepeers = [{
"playerID": user.playerID,
"playerName": user.playerName,
}];
}
}
$('#myTable').dataTable({
"aaData": goalkepeers,
"aoColumns": [{
"mDataProp": "playerID"
}, {
"mDataProp": "playerName"
},
]
});
Everything works fine but only one data is displayed in my table , the array should be like this 一切正常,但我的表中只显示一个数据,数组应该是这样的
goalkepeers = [{
"playerID": player1ID,
"playerName": player1Name,
},
{
"playerID": player2ID,
"playerName": player2Name,
}];
Any help will be appreciated , Thanks again :-) 任何帮助将不胜感激,再次感谢:-)
Try this, Declare goalkeepers globally and then declare goalkeeper everytime in the loop and push it into goalkeepers array: 试试这个,全局宣告守门员,然后每次在循环中宣告守门员并将其推入守门员阵列:
var goalkeepers = [];
for (var i = 0; i < json_parsed.Users.length; i++){
var user = json_parsed.Users[i];
if(user.position=="GK"){
var goalkeeper= {
"playerID": user.playerID,
"playerName":user.playerName,
};
goalkeepers.push(goalkeeper);
}
}
it happens because you're replacing the values: 它发生的原因是你要替换这些值:
var goalkepeers= [];
for (var i = 0; i < json_parsed.Users.length; i++){
var user = json_parsed.Users[i];
if(user.position=="GK"){
var obj={
"playerID": user.playerID,
"playerName":user.playerName,
};
goalkeepers.push(obj);
}
}
define the array before the loop 在循环之前定义数组
goldkeepers= array();
then inside the loop just do 然后在循环里面做
goalkepeers.push({
"playerID": user.playerID,
"playerName": user.playerName,
});
in your code your array is overwritten by the next json_parsed.Users element every time so the final result is an array with just the last element 在您的代码中,每次都会被下一个json_parsed.Users元素覆盖,因此最终结果是一个只有最后一个元素的数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.