如何在 JavaScript 中创建哈希或字典对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6298169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:09:50  来源:igfitidea点击:

How to create a hash or dictionary object in JavaScript

javascriptdictionary

提问by Saurabh Kumar

I want to create a map object in javascript. I came to the following idea:

我想在 javascript 中创建一个地图对象。我想到了以下想法:

 var a = new Array();
 a["key1"] = "value1";
 a["key2"] = "value2";

but then how I can find if a particular key exists or not?

但是我怎么能找到一个特定的键是否存在呢?

回答by Quentin

Don't use an array if you want named keys, use a plain object.

如果您想要命名键,请不要使用数组,请使用普通对象。

var a = {};
a["key1"] = "value1";
a["key2"] = "value2";

Then:

然后:

if ("key1" in a) {
   // something
} else {
   // something else 
}

回答by Facebook Staff are Complicit

A built-in Map type is now available in JavaScript. It can be used instead of simply using Object. It is supported by current versions of all major browsers.

JavaScript 现在可以使用内置的 Map 类型。它可以用来代替简单地使用 Object。所有主要浏览器的当前版本都支持它。

Maps do not support the [subscript]notation used by Objects. That syntax implicitly casts the subscriptvalue to a primitive string or symbol. Maps support any values as keys, so you must use the methods .get(key), .set(key, value)and .has(key).

地图不支持[subscript]对象使用的符号。该语法隐式地将subscript值转换为原始字符串或符号。Maps 支持任何值作为键,因此您必须使用方法.get(key),.set(key, value).has(key)

var m = new Map();
var key1 = 'key1';
var key2 = {};
var key3 = {};

m.set(key1, 'value1');
m.set(key2, 'value2');

console.assert(m.has(key2), "m should contain key2.");
console.assert(!m.has(key3), "m should not contain key3.");

Objects only supports primitive strings and symbols as keys, because the values are stored as properties. If you were using Object, it wouldn't be able to to distinguish key2and key3because their string representations would be the same:

对象仅支持原始字符串和符号作为键,因为值存储为属性。如果您使用的是 Object,它将无法区分key2key3因为它们的字符串表示形式相同:

var o = new Object();
var key1 = 'key1';
var key2 = {};
var key3 = {};

o[key1] = 'value1';
o[key2] = 'value2';

console.assert(o.hasOwnProperty(key2), "o should contain key2.");
console.assert(!o.hasOwnProperty(key3), "o should not contain key3."); // Fails!

Related

有关的

回答by Robert

You want to create an Object, not an Array.

你想创建一个对象,而不是一个数组。

Like so,

像这样,

var Map = {};

Map['key1'] = 'value1';
Map['key2'] = 'value2';

You can check if the key exists in multiple ways:

您可以通过多种方式检查密钥是否存在:

Map.hasOwnProperty(key);
Map[key] != undefined // For illustration // Edit, remove null check
if (key in Map) ...

回答by Howard

Use the inoperator: e.g. "key1" in a.

使用in运算符:例如"key1" in a

回答by KOGI

if( a['desiredKey'] !== undefined )
{
   // it exists
}