开发者

Setting array in javascript

开发者 https://www.devze.com 2023-03-12 08:01 出处:网络
Noob question. Setting array elements throws an error. I get this error when I run the script: array1[user_id] is undefined.

Noob question. Setting array elements throws an error.

I get this error when I run the script: array1[user_id] is undefined.

array1 = new Array();

// the data开发者_JAVA百科 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;
    }

}


First, you should not use an array, if you need a hash map, use objects. In some languages, it's one thing, but in JS they're not.

When defining a nested object you have to define each level as an object.

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;
    }    
}


If I understand this question correctly, you have to initialize the first dimension of array1 first, like so:

array1[user_id] = {};

then you can do this:

array1[user_id]['user'] = 'whatever';

That is of course assuming your user_id is not undefined.

0

精彩评论

暂无评论...
验证码 换一张
取 消