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

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

问题描述

我知道 JavaScript 中没有关联数组,只有对象.

但是我可以像这样使用括号表示法创建一个带有字符串键的数组:

var myArray = [];myArray['a'] = 200;myArray['b'] = 300;控制台日志(myArray);//打印 [a: 200, b: 300]

所以我想在不使用括号表示法的情况下做完全相同的事情:

var myNewArray = [a: 200, b: 300];//我收到错误 - 意外令牌:

这也不起作用:

var myNewArray = ['a': 200, 'b': 300];//同样的错误.为什么我不能创建?

解决方案

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

所以先看看你的代码:

var myArray = [];//创建一个新的数组对象myArray['a'] = 200;//将属性a设置为200myArray['b'] = 300;//将属性 b 设置为 300

了解myArray['a'] = 200;myArray.a = 200;相同很重要!>

所以从你想要的开始:你不能在一个语句中创建一个 JavaScript 数组并且不传递任何数字属性给它.

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

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

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

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

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:

This does not work either:

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

解决方案

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

It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!

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

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

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天全站免登陆