これまでに見つけたすべてのドキュメントは、すでに作成されているキーを更新するためのものです。
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.
ベストアンサー1
どういうわけか、すべての例はうまく機能しますが、複雑すぎます。
- 彼らは を使用していますが
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 ;-)
}