本文介绍了Javascript是否具有关联数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript是否具有关联数组?请解释.

Does Javascript have associative arrays? Please explain.

推荐答案

不; JavaScript数组只是数字键和混合值.使用对象可以达到相同的目的(或者,实际上,它与其他语言中的关联数组完全相同):

Nope; JavaScript arrays are just numeric keys and mixed values. The same thing can be achieved (or, actually, it's exactly the same as associative arrays in other languages) with objects:

var foo = {
  a: 123,
  b: 'CDE'
};

foo.a; // 123
foo['a']; // 123

您可以使用数组:

var foo = [];
foo.a = 123;
foo.b = 'CDE';

foo.b; // CDE
foo['b']; // CDE

但是,应该永远不要这样做,因为这不会将键/值对输入到数组中,而是将它们作为属性添加到数组对象中. (此外,{a: 123}a = []; a.a = 123容易).如果需要键/值对,请使用对象".如果需要枚举列表,请使用数组.

HOWEVER, this should never be done because this will not enter the key/value pairs into the array, but add them to the array object as properties. (besides, {a: 123} is easier than a = []; a.a = 123) If you need key/value pairs, use Objects. If you need an enumerated list, use arrays.

这篇关于Javascript是否具有关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:40