字符串作为数组的键 [英] Strings as keys of array

查看:150
本文介绍了字符串作为数组的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用字符串作为数组的键时,console表示没有这些声明值的数组,而在键为字符串的情况下以此值进行迭代时,不显示该数组吗? ,尽管我可以从中获得价值.

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 string aren't displayed? , although i can get value of them.

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

>> arr["something"] = "aught";
   "aught"

>> arr
   [0, 1, 2, 3]

>> arr["something"]
   "aught"

>> for( var i = arr.length; i--; console.log( arr[ i ] ) );
   3
   2
   1
   0

我了解数组是在JavaScript引擎中实现了某种枚举"接口的对象.

I understand that arrays are objects which has implemented some kind of 'enumerate' interface in JavaScript's engine.

最有趣的是,解释器不会引发警告或错误,所以我花了一些时间搜索可能丢失数据的地方.

Most interesting is that interpreter isn't throwing either warning or error, so I spent some time of searching for where data could be lost.

推荐答案

在javascript中,数组有2种类型:标准数组和关联数组

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

  • [ ]-标准数组-仅基于0的​​整数索引
  • { }-关联数组-键可以是任何字符串的javascript对象
  • [ ] - standard array - 0 based integer indexes only
  • { } - associative array - javascript objects where keys can be any strings

因此,当您定义:

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

您正在定义一个标准数组,其中索引只能是整数.当您执行arr["something"]时,由于something(用作索引的对象)不是整数,因此您基本上是在定义arr对象的属性(所有内容在javascript中都是对象).但是您没有在标准数组中添加元素.

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.

这篇关于字符串作为数组的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆