Does Javascript have associative arrays?

前端 未结 6 1017
[愿得一人]
[愿得一人] 2020-12-07 02:43

Does Javascript have associative arrays? Please explain.

6条回答
  •  -上瘾入骨i
    2020-12-07 03:07

    The closest we have is an object; the easiest way you can define this is using object literal syntax.

    var assocArray = {
       key: 1,
       key2: 2
    };
    

    You should be wary of a few things however:

    1. It does not have a .length property.
    2. You should use for in to iterative over it, rather than for(;;;);, but should combine it with hasOwnProperty():

      for (var x in assocArray) {
          if (assocArray.hasOwnProperty(x)) {
              // x = the key, assocArray[x] = the value 
          }
      }
      
    3. There is no concept of ordering/ sorting the members. Whilst all implementations I know of iterate the members in the order they were added, this is not standardised.

提交回复
热议问题