简体   繁体   中英

Appending to an object - javascript

If I do the following,

var array = [];
array['foo'] = [];
console.log(array.length)   // => 0

the console.log prints 0 length.

Is there a way to push key-value to arrays in javascript? Is it a bad idea in general? Do I need to keep the length updated myself?

There is the option to use bracket notation as recommended here ( SO - JavaScript Array Push key value ).

But later in the code I want to push to the object/array and SO recommends to use arrays again ( SO - Appending to an object ).

So I'm not quite sure which datastructure to use. For my task I guess I need key-values. Its an async-task and I can't rely on the order in an unnamed array. But from what I read so far, it seems kind of a hack to append to objects, too.

You can push an object:

var arr = [];
var obj = {foo: "bar"};
arr.push(obj);
arr.length; //1
arr[0].foo; //"bar"

You should probably use a javascript object , which acts as a key/value pair data structure (like a HashMap or a Dictionary ).

var data = {
  key: 'value'
}

data['key'] // 'value'
Object.keys(data).length // 1

For the sake of your future self, you should not add properties to an array nor try to simulate an array with an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM