205

これまでに見つけたすべてのドキュメントは、既に作成されているキーを更新することです。

 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.
4

9 に答える 9

491

どういうわけか、すべての例はうまく機能しますが、複雑すぎます。

  • 彼らは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 ;-)
}
于 2008-12-09T03:52:31.793 に答える
148

最初の例を使用します。キーが存在しない場合は追加されます。

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

「oscar」を含むメッセージ ボックスが表示されます。

試す:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );
于 2008-12-09T01:19:02.807 に答える
29

JavaScriptには連想配列がありませんオブジェクトがあります。

次のコード行はすべてまったく同じことを行います。オブジェクトの「name」フィールドを「orion」に設定します。

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

Arrayanも-であるため、連想配列があるように見えますが、Object実際には配列に何かを追加しているわけではありません。オブジェクトにフィールドを設定しています。

これで問題が解決したので、次の例に対する実用的なソリューションを示します。

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// Split into key and value
var kvp = cleaned.split('=');

// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.
于 2008-12-09T01:47:52.857 に答える
9

MK_Devに応答して、反復することはできますが、連続することはできません(そのためには、明らかに配列が必要です)。

Googleですばやく検索すると、JavaScriptでハッシュテーブルが表示されます

ハッシュ内の値をループするためのサンプルコード(前述のリンクから):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}
于 2008-12-09T01:37:24.453 に答える
5

元のコード (参照できるように行番号を追加しました):

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

もうすぐそこ...

  • trim1 行目: on textを実行する必要があるため、 name = oscar.

  • 3 行目:等号の前後に常にスペースがあれば問題ありません。1行目にない方がいいかもしれません。各keyValuePairtrimを使用してトリムします=

  • 3 の後と 4 の前に行を追加します。

      key = keyValuePair[0];`
    
  • 4 行目: 次のようになります。

      dict[key] = keyValuePair[1];
    
  • 5 行目: 次のように変更します。

      alert( dict['name'] );  // It will print out 'oscar'
    

dict[keyValuePair[0]]うまくいかないと言いたいのです。keyValuePair[0]文字列を設定し、それを連想キーとして使用する必要があります。それが私が仕事をする唯一の方法です。設定したら、数値インデックスまたはキーで引用符を使用して参照できます。

于 2009-10-19T19:10:28.890 に答える
4

最新のブラウザーはすべて、キー/値のデータ構造であるMapをサポートしています。Map を Object よりも使いやすくする理由はいくつかあります。

  • オブジェクトにはプロトタイプがあるため、マップにはデフォルトのキーがあります。
  • Object のキーは文字列であり、Map の任意の値にすることができます。
  • オブジェクトのサイズを追跡する必要があるときに、マップのサイズを簡単に取得できます。

例:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

他のオブジェクトから参照されていないキーをガベージ コレクションする場合は、Map の代わりにWeakMapを使用することを検討してください。

于 2015-05-07T02:42:13.280 に答える
1
var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

これは問題ありませんが、配列オブジェクトのすべてのプロパティを反復処理します。

プロパティ myArray.one、myArray.two... のみを反復処理する場合は、次のようにします。

myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(var i=0;i<maArray.length;i++){
    console.log(myArray[myArray[i]])
}

これで、myArray["one"] によるアクセスと、これらのプロパティを介した反復のみが可能になりました。

于 2012-03-22T16:14:32.567 に答える