javascript数组多维推送

时间:2015-06-07 05:14:31

标签: javascript

我想推送值多维数组。但我无法成功。

var e = [];
var data = [];  
var element = {}, items = [];
e = getelement("alan"); 

for(s=0;s < e.length ; s++ ){

element.resim = $( "#"+e[s] ).val();
element.baslik = $( "#"+e[s] ).val();
element.icerik = $( "#"+e[s] ).val();
element.links = $( "#"+e[s] ).val();
items.push(element);

}


c = JSON.stringify(items);

对象来源:

'0' => "resim" '1' => "baslik" '2' => "icerik" '3' => "link"

c对象来源:

[
    {"resim":"4","baslik":"4","icerik":"4","links":"4"},
    {"resim":"4","baslik":"4","icerik":"4","links":"4"},
    {"resim":"4","baslik":"4","icerik":"4","links":"4"},
    {"resim":"4","baslik":"4","icerik":"4","links":"4"}
]

2 个答案:

答案 0 :(得分:2)

您只能在element

中存储单个对象

每次绕过循环,你编辑现有对象,然后将另一个引用推送到数组上。

每次循环时都创建一个新对象。

for(s=0;s < e.length ; s++ ){
    element = {};

答案 1 :(得分:1)

每次推送到阵列时都不会创建新对象,因此您只需修改同一个对象并将其推入阵列4次。每次循环时都需要创建一个新对象:

var e = [];
var data = [];  
var items = [];
e = getelement("alan"); 

for(s=0;s < e.length ; s++ ){
    var element = {};
    element.resim = $( "#"+e[s] ).val();
    element.baslik = $( "#"+e[s] ).val();
    element.icerik = $( "#"+e[s] ).val();
    element.links = $( "#"+e[s] ).val();
    items.push(element);
}


c = JSON.stringify(items);