Javascript 在 jQuery 中创建对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5875060/
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
Creating an object array in jQuery
提问by Steven
I want to store an array of latitudes/longitudes. I have these inputs on my page:
我想存储一系列纬度/经度。我的页面上有这些输入:
<input type="hidden" class="latitude" value="-12.3456" />
<input type="hidden" class="longitude" value="12.3456" />
<input type="hidden" class="latitude" value="98.7654" />
<input type="hidden" class="longitude" value="-98.7654" />
And I'm putting them into arrays like so:
我将它们放入数组中,如下所示:
var latitudes = $('.latitude').map(function () { return this.value; }).get();
var longitudes = $('.longitude').map(function () { return this.value; }).get();
But I'm thinking that it would be better to store them in a single array as objects, so that I can say:
但我认为将它们作为对象存储在单个数组中会更好,这样我就可以说:
$.each(array, function (i, obj) {
alert(obj.Latitude);
alert(obj.Longitude);
});
How can I modify this to create an array of objects?
如何修改它以创建对象数组?
采纳答案by maerics
I would use jQuery.map():
我会使用jQuery.map():
$.map(latitudes, function(lat, i) {
return {latitude:lat, longitude:longitudes[i]};
});
回答by Abdullah Jibaly
var coords = [];
$.each(latitudes, function(index, value) {
coords.push({'Latitude': value, 'Longitude': longitudes[index]});
});
回答by James Montagne
This is one way:
这是一种方式:
var longs=$(".longitude");
var lats=$(".latitude");
var objs=[];
for(var i=0;i<Math.min(longs.length,lats.length);i++){
var obj={
"Latitude" : longs.eq(i).val(),
"Longitude" : lats.eq(i).val()
}
objs.push(obj);
}
I don't like to assume things are always in matching pairs, even if they should be. That's why the Math.min is there.
我不喜欢假设事物总是成对的,即使它们应该是。这就是 Math.min 存在的原因。