使用 jquery 创建动态数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4011840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create dynamic array with jquery
提问by Ozlem
I need some help regarding jquery arrays.
我需要一些有关 jquery 数组的帮助。
var queryArr;
$(markersArray).each(function(index) {
var _locationId = index;
var _locName = markersArray[index].name;
var _markerLat = markersArray[index].marker.getLatLng().lat();
var _markerLng = markersArray[index].marker.getLatLng().lng();
//I DO NOT KNOW THE SYNTAX BELOW HELP IN HERE PLEASE..
var locations = {
locationId:_locationId;
locationName:_locName,
lat:_markerLat,
lng:_markerLng }
queryStr = { "locations": locations} //??????????
});
queryArr.push(location); //???????
}
}
I need to reach each element by using sth like this:
我需要像这样使用 sth 来到达每个元素:
alert(queryArr[0].locations.locationId);
Obviously I will be using a for loop to reach each data by an index.
显然,我将使用 for 循环通过索引访问每个数据。
Can anyone give me example syntax for this.. I have found plenty examples of fixed arrays but not dynamic content.
任何人都可以为此提供示例语法。我找到了很多固定数组的示例,但没有找到动态内容。
回答by Rebecca Chernoff
You're very close. The line with push needs to be moved inside the .each() loop and you need to use queryStr for the push. Make sure you don't have any other syntax errors like missing semicolons.
你很亲近。带有 push 的行需要在 .each() 循环内移动,并且您需要使用 queryStr 进行推送。确保您没有任何其他语法错误,例如缺少分号。
queryArr.push(queryStr);
queryArr.push(queryStr);
Here's your example:
这是你的例子:
var queryArr = [];
$(markersArray).each(function(index) {
var _locationId = index;
var _locName = markersArray[index].name;
var _markerLat = markersArray[index].marker.getLatLng().lat();
var _markerLng = markersArray[index].marker.getLatLng().lng();
var locations = {
"locationId" :_locationId;
"locationName" :_locName,
"lat" :_markerLat,
"lng" :_markerLng
};
queryStr = { "locations" : locations };
queryArr.push(queryStr);
});
回答by Gadde
var elements = document.getElementsByTagName("div"); // returns a nodeList
var array = jQuery.makeArray(elements );
$(array ).appendTo(document.body);
or like
或喜欢
var object = $('li');
var array = $.makeArray(object);
回答by Ozlem
var queryArr=[];
for ( var index=0; index<markersArray.length; index++){
var _locationId = index;
var _locName = markersArray[index].name;
var _markerLat = markersArray[index].marker.getLatLng().lat();
var _markerLng = markersArray[index].marker.getLatLng().lng();
var locations = {
locationId:_locationId,
locationName:_locName,
lat:_markerLat,
lng:_markerLng }
queryStr = { "locations": locations}
queryArr.push(queryStr);
}
//test - works:)
for ( var i=0; i<markersArray.length; i++){
alert(
queryArr[i].locations.locationId+"--"+
queryArr[i].locations.locationName +"--"+
queryArr[i].locations.lat);
}