Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript关联数组中动态创建键(Dynamically creating keys in JavaScript associative array)

How can I dynamically create keys in javascript associative arrays?(如何在javascript关联数组中动态创建键?)

All the documentation I've found so far is to update keys that are already created:(到目前为止,我发现的所有文档都是更新已经创建的密钥:)

 arr['key'] = val;

I have a string like this " name = oscar "(我有这样的字符串" name = oscar ")

And I want to end up with something like this:(我想结束这样的事情:)

{ name: 'whatever' }

That is I split the string and get the first element, and I want to put that in a dictionary.(那就是我分割字符串并获取第一个元素,然后将其放入字典中。)

Code(码)

var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // prints nothing.
  ask by OscarRyz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Somehow all examples, while work well, are overcomplicated:(尽管所有示例都能很好地工作,但它们却过于复杂:)

  • They use new Array() , which is an overkill (and an overhead) for a simple associative array (AKA dictionary).(他们使用new Array() ,对于简单的关联数组(AKA字典)而言,这是多余的(和开销)。)
  • The better ones use new Object() .(更好的使用new Object() 。) Works fine, but why all this extra typing?(工作正常,但是为什么要进行所有这些额外的输入呢?)

This question is tagged "beginner", so let's make it simple.(这个问题被标记为“初学者”,因此让我们简化一下。)

The uber-simple way to use a dictionary in JavaScript or "Why JavaScript doesn't have a special dictionary 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];

Now let's change values:(现在让我们更改值:)

// change the value of fred
dict.fred = "astra";
// the assignment creates and/or replaces key-value pairs

// change 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) {
  // 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]);
  }
}

Deleting values is easy too:(删除值也很容易:)

// let's delete fred
delete dict.fred;
// fred is removed, 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,
  // 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 ;-)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...