2010-10-31 21 views
0

我试图使用USERBOX插件,在这个例子中,我们有以下阵列正在兴建的Javascript转换为例,真正的代码问题 - 阵列

var data = [ 
    {text: "Adam Adamson", id: "[email protected]"}, 
    {text: "Betsy Boop",  id: "[email protected]"}, 
    {text: "Jooles Jooles", id: "[email protected]"} 
]; 

我要建立使用JSON我在运行时数组我从我的web服务收到的数据。 在我的代码中,我试图用下面的方法来模仿这个数组。

var data = new Array(); 

    for (var i = 0; i < msg.d.ListExercise.length; i++) { 
     $("userlist").append("msg.d.ListExercise[i].exercise_value"); 
     if (i > 0 && i < msg.d.ListExercise.length - 1) { 
      data.push('{text: ' + '"' + msg.d.ListExercise[i].exercise_value + '"' + ' , id: ' + '"' + msg.d.ListExercise[i].exercise_id + '"' + '},'); 
     } 
     if (i == msg.d.ListExercise.length - 1) { 
      data.push('{text: ' + '"' + msg.d.ListExercise[i].exercise_value + '"' + ' , id: ' + '"' + msg.d.ListExercise[i].exercise_id + '"' + '}'); 
     } 
    } 

从我所了解的例子中他建立了一个字符串数组。我已经验证数组正在被添加到数据并且数据正在被添加到它。但是,当我将数组传递给插件代码时,它显示单词'Undefined'135次(数组的长度)。

我的数组看起来是这样的:

{text: "Standard Push-Up" , id: "1"}, 
{text: "Wide Front Pull-Up" , id: "2"}, 
{text: "Vertical Punches" , id: "135"} 

是什么让我的数据到在JavaScript他的阵列例子的最佳方式?

+1

丢失单引号。你现在正在推弦乐,而不是对象 – mplungjan 2010-10-31 17:12:40

+0

@mplungjan - 谢谢,你是对的! – webdad3 2010-10-31 17:33:39

回答

2

你应该建立一个哈希数组,而不是看起来像散列的字符串数组。你需要像

data.push({text: msg.d.ListExercise[i].exercise_value, id: msg.d.ListExercise[i].exercise_id });

1

目前你推到字符串数组,只是去掉引号所以你推对象,像这样:

var data = []; 
for (var i = 0; i < msg.d.ListExercise.length; i++) { 
    data.push({ text: msg.d.ListExercise[i].exercise_value, id: msg.d.ListExercise[i].exercise_id }); 
} 

或者因为您所标记的问题jQuery,使用$.map()这样的:

var data = $.map(msg.d.ListExercise, function() { 
    return { text: this.exercise_value, id: this.exercise_id }; 
}); 
+0

我试过了$ .map的功能,它什么都没有返回......我是否必须将该代码放入循环中,还是应该循环遍历数据并将其自动添加到数组中? – webdad3 2010-10-31 17:33:10

+0

@Jeff - 啊废话我在变量副本上留下了'.length',更新后的版本应该可以工作,它会替换你问题中的所有代码。 – 2010-10-31 17:35:16