Javascript将示例转换为实际代码问题-数组
我正在尝试使用userBox插件,在示例中,我们正在构建以下阵列:Javascript将示例转换为实际代码问题-数组,javascript,jquery,Javascript,Jquery,我正在尝试使用userBox插件,在示例中,我们正在构建以下阵列: var data = [ {text: "Adam Adamson", id: "adam@test.com"}, {text: "Betsy Boop", id: "betsy@test.com"}, {text: "Jooles Jooles", id: "julie@test.com"} ]; 我希望在运行时使用从Web服务接收的JSON数据构建阵列。 在我的代码中,我尝试用以
var data = [
{text: "Adam Adamson", id: "adam@test.com"},
{text: "Betsy Boop", id: "betsy@test.com"},
{text: "Jooles Jooles", id: "julie@test.com"}
];
我希望在运行时使用从Web服务接收的JSON数据构建阵列。
在我的代码中,我尝试用以下方法模拟这个数组
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 + '"' + '}');
}
}
用javascript将我的数据放入他的数组示例的最佳方法是什么?您应该构建一个哈希数组,而不是一个看起来像哈希的字符串数组。你需要像这样的东西
data.push({text:msg.d.ListExercise[i].exercise\u值,id:msg.d.ListExercise[i].exercise\u id})代码>您应该构建一个哈希数组,而不是一个看起来像哈希的字符串数组。你需要像这样的东西
data.push({text:msg.d.ListExercise[i].exercise\u值,id:msg.d.ListExercise[i].exercise\u id})代码>当前,您正在将字符串推送到数组中,只需删除引号即可推送对象,如下所示:
{text: "Standard Push-Up" , id: "1"},
{text: "Wide Front Pull-Up" , id: "2"},
{text: "Vertical Punches" , id: "135"}
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 });
}
var data = $.map(msg.d.ListExercise, function() {
return { text: this.exercise_value, id: this.exercise_id };
});
当前,您正在将字符串推送到数组中,只需删除引号即可推送对象,如下所示:
{text: "Standard Push-Up" , id: "1"},
{text: "Wide Front Pull-Up" , id: "2"},
{text: "Vertical Punches" , id: "135"}
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 });
}
var data = $.map(msg.d.ListExercise, function() {
return { text: this.exercise_value, id: this.exercise_id };
});
丢失单引号。你现在是在推波助澜,不是吗objects@mplungjan-谢谢,你说得对!丢失单引号。你现在是在推波助澜,不是吗objects@mplungjan-谢谢,你说得对!我尝试了$.map功能,但它没有返回任何结果。。。我必须将该代码放入循环中,还是应该循环数据并自动将其添加到数组中?@Jeff-ah crap我在变量副本中留下了一个.length
,更新的版本应该可以工作,它将替换您问题中的所有代码。我尝试了$.map功能,但它没有返回任何结果。。。我必须将代码放入循环中,还是应该循环数据并自动将其添加到数组中?@Jeff-ah crap我在变量副本中留下了一个.length
,更新的版本应该可以工作,它将替换您问题中的所有代码。