1

This should be pretty easy but I'm a little confused here. I want to fill this object:

var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };

but in the start I have this:

var obj = {};

I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?

4

3 回答 3

3

You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:

var obj = {};

for (var k = 0; k<10; k++) {
    obj['customkey'+k] = 'some'+k;
}

This would return:

obj {
    customkey0 : 'some0',
    customkey1 : 'some1',
    customkey2 : 'some2',
    ...
}

Keep in mind, an array: ['some1','some2'] is basicly like and object: { 0 : 'some1', 1 : 'some2' } Where an object replaces the "index" (0,1,etc) by a STRING key. Hope this helps.

于 2013-04-15T17:17:45.230 回答
1

push() is for use in arrays, but you're creating a object.

You can add properties to an object in a few different ways:

obj.one = some1;

or

obj['one'] = some1;
于 2013-04-15T17:15:01.800 回答
0

I would write a simple function like this:

 function pushVal(obj, value) {
     var index = Object.size(obj);
     //index is modified to be a string.
     obj[index] = value;
 }

Then in your code, when you want to add values to an object you can simply call:

  for(var i=0; i<someArray.length; i++) {
      pushVal(obj, someArray[i]);
   }

For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.

EDIT

Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:

function pushVal(obj, value, key) {
     //index is modified to be a string.
     obj[key] = value;
 }

 or 

 obj[key] = value;     

I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).

于 2013-04-15T17:19:43.860 回答