不知何故,所有的例子虽然效果很好,但都过于复杂:
- 他们使用 ,这是一个简单的关联数组(AKA字典)的过度杀伤(和开销)。
new Array()
- 使用效果越好。它工作正常,但是为什么所有这些额外的输入?
new Object()
这个问题被标记为“初学者”,所以让我们让它变得简单。
在JavaScript中使用字典的非常简单的方法或“为什么JavaScript没有特殊的字典对象?”:
// Create an empty associative array (in JavaScript it is called ... Object)
var dict = {}; // Huh? {} is a shortcut for "new Object()"
// Add a key named fred with value 42
dict.fred = 42; // We can do that because "fred" is a constant
// and conforms to id rules
// Add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!"; // We use the subscript notation because
// the key is arbitrary (not id)
// Add an arbitrary dynamic key with a dynamic value
var key = ..., // Insanely complex calculations for the key
val = ...; // Insanely complex calculations for the value
dict[key] = val;
// Read value of "fred"
val = dict.fred;
// Read value of 2bob2
val = dict["2bob2"];
// Read value of our cool secret key
val = dict[key];
现在让我们更改值:
// Change the value of fred
dict.fred = "astra";
// The assignment creates and/or replaces key-value pairs
// Change the value of 2bob2
dict["2bob2"] = [1, 2, 3]; // Any legal value can be used
// Change value of our secret key
dict[key] = undefined;
// Contrary to popular beliefs, assigning "undefined" does not remove the key
// Go over all keys and values in our dictionary
for (key in dict) {
// A for-in loop goes over all properties, including inherited properties
// Let's use only our own properties
if (dict.hasOwnProperty(key)) {
console.log("key = " + key + ", value = " + dict[key]);
}
}
删除值也很容易:
// Let's delete fred
delete dict.fred;
// fred is removed, but the rest is still intact
// Let's delete 2bob2
delete dict["2bob2"];
// Let's delete our secret key
delete dict[key];
// Now dict is empty
// Let's replace it, recreating all original data
dict = {
fred: 42,
"2bob2": "twins!"
// We can't add the original secret key because it was dynamic, but
// we can only add static keys
// ...
// oh well
temp1: val
};
// Let's rename temp1 into our secret key:
if (key != "temp1") {
dict[key] = dict.temp1; // Copy the value
delete dict.temp1; // Kill the old key
} else {
// Do nothing; we are good ;-)
}