簡體   English   中英

在 JavaScript 關聯數組中動態創建鍵

[英]Dynamically creating keys in a JavaScript associative array

到目前為止我找到的所有文檔都是更新已創建的密鑰:

 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 ;-)
}

使用第一個例子。 如果密鑰不存在,它將被添加。

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]] );

JavaScript沒有關聯數組 它有對象

以下代碼行都做完全相同的事情 - 將對象上的“名稱”字段設置為“獵戶座”。

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';

看起來您有一個關聯數組,因為Array也是一個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.

作為對 MK_Dev 的響應,可以迭代,但不能連續迭代(為此,顯然需要一個數組)。

一個快速的谷歌搜索帶來了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]);
}

原始代碼(我添加了行號,因此可以參考它們):

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.

差不多好了...

  • 第 1 行:您應該對文本進行trim ,使其成為name = oscar

  • 第 3 行:好的,只要你的等號周圍總是有空格。 最好不要在第 1 行trim 。使用=並修剪每個 keyValuePair

  • 在 3 之后和 4 之前添加一行:

     key = keyValuePair[0];`
  • 第 4 行:現在變成:

     dict[key] = keyValuePair[1];
  • 第 5 行:更改為:

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

我想說dict[keyValuePair[0]]不起作用。 您需要將一個字符串設置為keyValuePair[0]並將其用作關聯鍵。 這是我讓我的工作的唯一途徑。 設置完成后,您可以使用數字索引或鍵入引號來引用它。

所有現代瀏覽器都支持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"

如果您希望未從其他對象引用的鍵被垃圾收集,請考慮使用WeakMap而不是 Map。

我認為如果你像這樣創建它會更好:

var arr = [];

arr = {
   key1: 'value1',
   key2:'value2'
};

有關更多信息,請查看以下內容:

JavaScript 數據結構 - 關聯數組

var obj = {};

for (i = 0; i < data.length; i++) {
    if(i%2==0) {
        var left = data[i].substring(data[i].indexOf('.') + 1);
        var right = data[i + 1].substring(data[i + 1].indexOf('.') + 1);

        obj[left] = right;
        count++;
    }
}

console.log("obj");
console.log(obj);

// Show the values stored
for (var i in obj) {
    console.log('key is: ' + i + ', value is: ' + obj[i]);
}


}
};
}
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"] 訪問這兩個屬性,並且只能遍歷這些屬性。

 const arrayValues = [ "yPnPQpdVgzvSFdxRoyiwMxcx", "yPnPQpdVgzvSFdxRoyiwMxcx", "a96b3Z-rqt6U3QV_1032fxcsa", "iNeoJfVnF7dXqARwnDOhj233dsd" ]; const newArr = arrayValues.map((x)=>{ return { "_id":x } }); console.log(newArr)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM