gpt4 book ai didi

javascript - 在 JavaScript 关联数组中动态创建键

转载 作者:IT老高 更新时间:2023-10-28 13:14:38 24 4
gpt4 key购买 nike

到目前为止,我发现的所有文档都是更新已创建的 key :

 arr['key'] = val;

我有一个这样的字符串:"name = oscar "

我想以这样的方式结束:

{ name: 'whatever' }

即拆分字符串,获取第一个元素,然后将其放入字典中。

代码

var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // Prints nothing.

最佳答案

不知何故,所有示例虽然运行良好,但都过于复杂:

  • 他们使用 new Array(),这对于简单的关联数组(AKA 字典)来说是一种过度杀伤(和开销)。
  • 更好的使用 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 ;-)
}

关于javascript - 在 JavaScript 关联数组中动态创建键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/351495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com