Dynamiczne tworzenie kluczy w tablicy asocjacyjnej JavaScript

Cała dokumentacja, którą do tej pory znalazłem, polega na aktualizacji kluczy, które zostały już utworzone:

 arr['key'] = val;

Mam taki ciąg: " name = oscar "

A ja chcę skończyć z czymś takim:

{ name: 'whatever' }

To znaczy, podzielić łańcuch i uzyskać pierwszy element, a następnie umieścić go w słowniku.

Kod

var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // Prints nothing.
Author: OscarRyz, 2008-12-09

9 answers

Użyj pierwszego przykładu. Jeśli klucz nie istnieje, zostanie dodany.

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

Wyświetli okno wiadomości zawierające 'oscar'.

Try:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );
 147
Author: tvanfosson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-03 01:40:01

Jakoś wszystkie przykłady, choć działają dobrze, są zbyt skomplikowane:

  • używają new Array(), który jest overkill (i overhead) dla prostej tablicy asocjacyjnej (aka dictionary).
  • ci lepsi używają new Object(). Działa dobrze, ale po co to dodatkowe pisanie?

To pytanie jest oznaczone jako "początkujący", więc zróbmy to prosto.

Über-prosty sposób użycia słownika w JavaScript lub " dlaczego JavaScript nie ma specjalnego obiektu słownika?":

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

Teraz zmieńmy wartości:

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

Usuwanie wartości jest również łatwe:

// 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 ;-)
}
 490
Author: Eugene Lazutkin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-20 10:59:39

JavaScript nie posiada tablic asocjacyjnych . Posiada obiekty .

Następujące linie kodu robią dokładnie to samo - ustaw pole 'name' NA obiekcie na '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';

Wygląda na to, że masz tablicę asocjacyjną, ponieważ Array jest również Object - jednak w rzeczywistości nie dodajesz rzeczy do tablicy; ustawiasz pola na obiekcie.

Teraz, gdy już to wyjaśniliśmy, oto działające rozwiązanie twojego przykładu:

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.
 29
Author: Orion Edwards,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-20 10:53:48

W odpowiedzi na MK_Dev, można iterować, ale nie kolejno (do tego oczywiście potrzebna jest tablica).

Szybkie wyszukiwanie Google wyświetla tabele hash w JavaScript .

Przykładowy kod do zapętlania wartości w hashu (z wyżej wymienionego linku):

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]);
}
 9
Author: Danny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-20 10:51:48

Oryginalny kod (dodałem numery linii, więc mogę się do nich odwoływać):

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.
Już prawie...
  • Linia 1: powinieneś zrobić {[4] } na tekście, więc jest to name = oscar.

  • Linia 3: dobrze tak długo jak ty zawsze masz spacje wokół siebie. Może lepiej nie być trim w linii 1. Użyj = i przyciąć każdy keyValuePair

  • Dodaj wiersz po 3 i przed 4:

      key = keyValuePair[0];`
    
  • Linia 4: Teraz staje się:

      dict[key] = keyValuePair[1];
    
  • Linia 5: Zmień na:

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

Próbuję powiedzieć, że dict[keyValuePair[0]] nie działa. Musisz ustawić łańcuch znaków na keyValuePair[0] i użyć go jako klucza asocjacyjnego. To jedyny sposób, żeby mój zadziałał. Po skonfigurowaniu można odwoływać się do niego za pomocą indeksu numerycznego lub klucza w cudzysłowie.

 5
Author: Andrea,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-20 11:02:05

Wszystkie nowoczesne przeglądarki obsługują mapę , która jest strukturą danych klucz/wartość. Jest kilka powodów, które sprawiają, że korzystanie z mapy jest lepsze niż obiekt:

  • obiekt ma prototyp, więc na mapie są domyślne klucze.
  • Klucze obiektu są ciągami znaków, gdzie mogą być dowolną wartością dla mapy.
  • możesz łatwo uzyskać Rozmiar mapy, podczas gdy musisz śledzić rozmiar obiektu.

Przykład:

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"

Jeśli chcesz klucze które nie są przywoływane z innych obiektów jako śmieci, rozważ użycie WeakMap zamiast mapy.

 4
Author: Vitalii Fedorenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-20 11:06:35

Myślę, że lepiej będzie, jeśli po prostu stworzysz go w ten sposób:

var arr = [];

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

Aby uzyskać więcej informacji, spójrz na to:

JavaScript Data Structures-Asocjacyjna Tablica

 3
Author: Karim Samir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-20 11:07:12
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]);
}


}
};
}
 1
Author: user2266928,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-20 11:08:28
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]);
}

To jest w porządku, ale iteracja przez każdą właściwość obiektu array.

Jeśli chcesz tylko iterować poprzez właściwości myArray.jeden, myArray.dwa... spróbuj tak:

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

Teraz możesz uzyskać dostęp zarówno przez myArray ["one"], jak i iterację tylko za pośrednictwem tych właściwości.

 1
Author: Sasinda Rukshan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-08-04 06:42:06