How to store objects in a array using javascript

2020-04-21 08:04发布

问题:

i am developing extesnions for safari browswer. i want to store current active tab objects in a array as key. how to store multiple tab objects in a array.

i wrote following code.

**First scenario:

var obj = {};

obj1=new Object();
obj2=new Object();
obj3=new Object();

obj['cTab_'+obj1] = "This is object1";
obj['cTab_'+obj2] = "This is object2";
obj['cTab_'+obj3] = "This is object3";**

prblem is i am getting 3rd object value. how to get all the object values.

**Second scenario:

var arr = new Array();

cTabObj1 = new Object();
arr[cTabObj1] = 'This is cTabObj1 Value';

cTabObj2 = new Object();
arr[cTabObj2] = 'This is cTabObj2 Value';

cTabObj3 = new Object();
arr[cTabObj3] = 'This is cTabObj3 Value';

alert("arr[cTabObj1]    :" + arr[cTabObj1] + " arr[cTabObj2]    :" + arr[cTabObj2] + " arr[cTabObj3]    :" + arr[cTabObj3]);**

Here also i am getting "This is cTabObj3 Value" for all three object

Thanks in advance.

回答1:

i want to store current active tab objects in a array as key

You can't do that. Keys are strings. They always are strings.

If you take a look at the array you will find any object gets converted to "[object Object]" so your basically inserting the same key 3 times.

Use console.log(arr) or console.dir(arr) together with firebug or chrome/opera/safari

What you want is a ES6 WeakMap.

Only Firefox6 implements WeakMap



回答2:

The keys need to be strings.

Try implementing the toString method on your objects so that it returns a unique identifier for each object. Then 'cTab_' + obj will be a unique string.



回答3:

You should rather store like this

cTabObj1 = new Object();
arr["cTabObj1"] = cTabObj1;


回答4:

Your first scenario is the way to go except that you have assigned the same subscript key to each object that you are storing in obj. When you use anything other than a string for an object property key, the value has toString() called on it internally, so

obj['cTab_'+obj1] = "This is object1";
obj['cTab_'+obj2] = "This is object2";
obj['cTab_'+obj3] = "This is object3";

will all have the same key of cTab_[object Object].

What you need is to differentiate the keys. Since each object will return "[object Object]" when toString() is called on it, you can remove the object from the property key too as it is redundant e.g.

var obj = {};
obj['cTab1'] = "This is object1";
obj['cTab2'] = "This is object2";
obj['cTab3'] = "This is object3";

or more tersely

var obj = {
    cTab1 : "This is object1",
    cTab2 : "This is object2",
    cTab3 : "This is object3"
};

The reason why the second way is not the way to go is that you are trying to use a JavaScript array like an associative array, which they are not; it may seem to work at first but then you will discover some very odd behaviour, such as arr.length does not count them as items in the array, etc. For more details, read the linked article. You want to use Object ({}) for this.