Strings as keys of array

前端 未结 2 1258
北海茫月
北海茫月 2020-11-30 03:26

When using strings as keys of an array, console is showing that the array without these declared values and while iterating by this values where keys are strin

相关标签:
2条回答
  • 2020-11-30 04:08

    In javascript there are 2 type of arrays: standard arrays and associative arrays

    • [ ] - standard array - 0 based integer indexes only
    • { } - associative array - javascript objects where keys can be any strings

    So when you define:

    var arr = [ 0, 1, 2, 3 ];
    

    you are defining a standard array where indexes can only be integers. When you do arr["something"] since something (which is what you use as index) is not an integer you are basically defining a property to the arr object (everything is object in javascript). But you are not adding an element to the standard array.

    0 讨论(0)
  • 2020-11-30 04:30

    for( var i = arr.length; i--; console.log( arr[ i ] ) );

    This will only give you the numeric indices, of course, but you can still loop over both numeric indices and string keys of your array like this:

    for (var x in arr) {
        console.log(x + ": " + arr[x]);
    }
    /* (console output):
         0: 0
         1: 1
         2: 2
         3: 3
         something: aught
    */
    
    0 讨论(0)
提交回复
热议问题