why does myArray.length is 3 here? I have added a new property in it, to my guess, it should be 4.
var myArray = [ "foo", 42, "bar" ];
myArray.baz = "baz";
myArray.length; // 3
You need to use Array.prototype.push() to add new elements to array. In your code myArray.baz = "baz" doesn't do anything.
var myArray = [ "foo", 42, "bar" ];
// your approch
myArray.baz = "baz";
console.log(myArray.length); // 3
console.log(myArray) // [ "foo", 42, "bar" ]
// correct
myArray.push("baz")
console.log(myArray.length); // 4
console.log(myArray) // [ "foo", 42, "bar", "baz" ]
unshift, or splice, or myArray[3] = 'baz' ... have I missed any?myArray.baz = 'baz' certainly DOES do something. It adds the property baz with the value baz to myArray
- In the first line, you create a variable
myArrayand you add a value to it. Every variable in Javascript is an object, that has keys and properties (see more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
Between [] you create an array type, that stores data and labels them with numbers. (see more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
- In the second line, you add a
bazproperty tomyArraywith"baz"value
- In the third line, you get the length property of the array
If you want to add a(n)
"baz"element to the end of the array, you can use the.push()method. For example:myArray.push("baz");
.push always gets a mention, but what about .unshift, or .splice, or myArray[3] = 'baz' - why are they ignored options?.push().length property is counting how many elements are in the array, not how many js object properties have it. In other languages, you can not add plus property to an array. Js is a high abstraction language, therefore you can do this strange thing.
lengthand the property calledmap, andfind, andreduce.... many many properties, but these are not included inlengtheither ... the Array "length" property (I linked to some useful documentation you can read) is not a count of properties, it is always numerically greater than the highest index in the array. index being a NUMBER - and that number is2, therefore index is (at least) 3, because there are entries at 0, 1 and 2 onlylengthis unaffected by non-numeric properties, and the array methods I mentioned before will not iterate over those non-numeric properties ... but it's perfectly OK (not advisable) to add properties to an array