javascript - What is the length of an array after both pushing to it, and assigning key-value pairs like an object -


this example :

var myarray = [] myarray.push('a string') console.log(myarray.length) // got: 1 myarray['arandomkey']='an other string' console.log(myarray.length) // got: 1 

so second element not added array length have not changed. when log array :

console.log(myarray) // got: ["a string", arandomkey: "an other string"] 

i see myarray has 2 elements ... what's going on ?

jsfiddle demo

var myarray = [] myarray.push('a string') console.log(myarray.length) // got: 1 myarray['arandomkey']='an other string' console.log(myarray.length) // got: 1 

few more things

myarray[1] = "2nd string"; console.log(myarray.length);// you'll 2  console.log(myarray.arandomkey); // other string console.log(myarray["arandomkey"]); // other string console.log(myarray) // ["a string", "2nd string", arandomkey: "an other string"] 

by looking @ above statements, if use push() or assign using integer key myarray[1], value gets pushed array. if add non-number key instead of integer, still gets added array object property doesn't pushed item , can accessed object notation above.

note: beware while adding item array in fashion myarray[1] = "2nd string"; example, if write myarray[1000] = "2nd string";console.log(myarray), result looks ["a string", 1000: "2nd string", arandomkey: "an other string"] , length 1001


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -