gpt4 book ai didi

javascript - 在 JavaScript 中设置数组

转载 作者:行者123 更新时间:2023-12-02 20:15:54 24 4
gpt4 key购买 nike

菜鸟问题。设置数组元素会引发错误。

运行脚本时出现此错误:array1[user_id] 未定义。

array1 = new Array();

// the data variable I got from a JSON source
// using jQuery
$.each(data, function(i, item) {

// Set variables
user_id = item.post.user_id;
user = item.post.user;
price = item.post.price;

if (array1[user_id]['user'] != user) {
array1[user_id]['price'] = price;
array1[user_id]['user'] = user;
}

}

最佳答案

首先,你不应该使用数组,如果你需要 HashMap ,请使用对象。在某些语言中,这是一回事,但在 JS 中却不是。

定义嵌套对象时,您必须将每个级别定义为一个对象。

var hash = {};

// the data variable I got from a JSON source
$.each(data, function(i, item) {

// Set variables
user_id = item.post.user_id;
user = item.post.user;
price = item.post.price;
// Have to define the nested object
if ( !hash[user_id] ) {
hash[user_id] = {};
}
if (hash[user_id]['user'] != user) {
hash[user_id]['price'] = price;
hash[user_id]['user'] = user;
}
}

关于javascript - 在 JavaScript 中设置数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6313254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com