如何以JavaScript文字表示法创建关联数组 [英] How to create an associative array in JavaScript literal notation

查看:76
本文介绍了如何以JavaScript文字表示法创建关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到JavaScript中没有关联数组,只有 objects .

I understand that there are no associative arrays in JavaScript, only objects.

但是我可以使用括号符号使用字符串键创建 array ,如下所示:

However I can create an array with string keys using bracket notation like this:

var myArray = [];
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray); // Prints [a: 200, b: 300]

所以我想做完全相同的事情而不使用括号符号:

So I want to do the exact same thing without using bracket notation:

var myNewArray = [a: 200, b: 300]; // I am getting error - Unexpected token:

这也不起作用:

var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?

推荐答案

JavaScript没有关联数组,只有对象.甚至JavaScript数组基本上也只是对象,只是特殊的是属性名称是数字(0,1,...).

JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).

因此,请先查看您的代码:

So look at your code first:

var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300

重要的是要了解myArray['a'] = 200;myArray.a = 200;相同

因此,从您想要的内容开始: 您无法创建JavaScript数组,也不能在一个语句中将数字属性传递给它.

So to start with what you want: You can't create a JavaScript array and pass no number attributes to it in one statement.

但这可能不是您所需要的!可能您只需要一个JavaScript对象,该对象与关联数组,字典或其他语言的映射基本上相同:它将字符串映射为值.这很容易做到:

But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:

var myObj = {a: 200, b: 300};

但是重要的是要了解这与您所做的略有不同. myObj instanceof Array将返回false,因为myObj不是原型链中Array的祖先.

But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.

这篇关于如何以JavaScript文字表示法创建关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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