字符串作为JavaScript数组的钥匙 [英] Strings as keys of array in javascript

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

问题描述

为什么要使用字符串作为数组键,控制台显示该数组没有这些声明的值,并在此值,其中键是遍历字符串不显示?虽然我可以让他们的价值。

Why using strings as keys of array, console is showing that 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引擎对象。
最有意思的是,国米preTER 是不扔警告或错误,所以我花了几天的搜索,其中数据可能丢失的时间。
我现在,我错了,我用 [] 而不是 {}

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 a few of time of searching for where the data could be lost. I now, I was wrong and I used [] instead of {}

推荐答案

在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 ];

要定义一个标准的数组,其中指标只能是整数。当你做改编[东西] ,因为的东西(这是你作为指数使用的)是不是整数你基本上是定义一个属性添加到改编对象(一切都在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.

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

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