JavaScript-声明关联数组的简短方法 [英] JavaScript - short way of declaring an associative array

查看:130
本文介绍了JavaScript-声明关联数组的简短方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有像PHP中那样声明关联数组的简短方法?

Is there a short way of declaring an associative array like in PHP?

$myArray = array('a' => 'b'); // PHP Way

在JavaScript中,我可以这样操作:

In JavaScript I'd do it this way:

var myArray = [];
myArray['a'] = 'b';

我不是在寻找JavaScript对象.

推荐答案

JavaScript没有关联数组.在您的示例中,您将myArray声明为数组,但随后为其分配了一个对象.因此,您的代码与此不同:

JavaScript does not have associative arrays. In your example, you declare myArray as array but then you assign an object to it. So your code is not different from this:

var myObject = {};
myObject['a'] = 'b';

更新:稍作修正.实际上,原始代码不会破坏数组.它只是将常规属性添加到它.这是可能的,因为JavaScript数组是JavaScript对象的子集.

Update: A little correction. Actually, the original code does not destroy the array. It just appends a regular property to it. That's possible because JavaScript arrays are a subset of JavaScript objects.

这篇关于JavaScript-声明关联数组的简短方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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