热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

字符串作为javascript数组的键-Stringsaskeysofarrayinjavascript

Whyusingstringsaskeysofarray,consoleisshowingthatarraywithoutthesedeclaredvaluesand

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.

为什么使用字符串作为数组的键,console显示没有声明值的数组,并在不显示键的值的情况下迭代这些值?,虽然我可以得到它们的价值。

>> 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

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 个解决方案

#1


69  

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

在Javascript中有两种类型的数组:标准数组和关联数组

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

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.

您正在定义一个标准数组,其中索引只能是整数。当你做arr(“某物”)的时候(你使用的是索引)不是一个整数,你基本上是在给arr对象定义一个属性(所有东西都是Javascript的对象)。但您并没有向标准数组添加元素。

#2


9  

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

for(var i = arr.length);我,;控制台。测井(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
*/

推荐阅读
author-avatar
长白山天翼张薇_955
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有