This is a basic question but I'm just curious about an elegant way to do something (I already have solution for dirty way). I have the code below to start with empty var a as JSON array. Then I want to concat more JSON objects array into it later on:
var a = [{}];
a = a.concat([{"a":"b1"},{"a":"b2"}]);
a.splice(0,1); // This does not work to remove index 0 of undefined
console.log(a[0].a + " " + a[1].a + " " + a[2].a);
The problem is when a declared, it already came with undefined in index 0. I could re-generate the whole array to remove all undefined using push.apply() but that seems unnecessary overhead. See:
Javascript: How to remove an array item(JSON object) based on the item property value?
Two questions:
- Is there a way to
concatarrays but override the index 0 on initialconcat? - OR is there a way to use
concatwithout declaring ita = [{}]?
a = []?undefinedin index 0; it has an empty object. If you declare the array with just[], then it will have a length of 0.a[2].aat the console.log line? At that point, there's nota[2]. Before the console.log call, there's no error.