javascript - Why doesn't the length of the array change when I add a new property? -


var arr = ["hello", "there", 123, 456, {      show: function (value) {          alert(value);      }  }];  arr[4].show(arr[0]);  arr["hello"] = {      damn: function () {          alert("what's happening yo !");      }  }  arr.hello.damn();  alert("arr length is: " + arr.length);

quoting ecma script 5 specification of array objects,

a property name p (in form of string value) array index if , if tostring(touint32(p)) equal p , touint32(p) not equal 232−1.

since hello not valid, according above definition, not considered array index ordinary property.

quoting mdn's relationship between length , numerical properties section,

when setting property on javascript array when property valid array index , index outside current bounds of array, engine update array's length property accordingly

so, if property valid array index, length property adjusted.

in case, have created new property hello on array object.


note: numerical properties used in of array's prototype functions, foreach, map, etc.

for example, array shown in question, when used foreach,

arr.foreach(function(currentitem, index) {     console.log(currentitem, index); }) 

would print

hello 0 there 1 123 2 456 3 { show: [function] } 4 

even though list of keys shows hello.

console.log(object.keys(arr)); // [ '0', '1', '2', '3', '4', 'hello' ] 

it because, array derived object,

console.log(arr instanceof object); // true 

and hello valid key of array object, not valid array index. so, when treat array object, hello included in keys, array specific functions include numerical properties.


Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -