자바 스크립트 연관 배열에서 키를 동적으로 생성하려면 어떻게해야합니까?
지금까지 찾은 모든 문서는 이미 작성된 키를 업데이트하는 것입니다.
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.
답변
첫 번째 예를 사용하십시오. 키가 존재하지 않으면 추가됩니다.
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]] );
답변
어떻게 든 모든 예제가 잘 작동하지만 지나치게 복잡합니다.
- 이들은 사용
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 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]);
}
}
값을 삭제하는 것도 쉽습니다.
// 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 ;-)
}
답변
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';
당신이 연관 배열이 같은이 때문에 같습니다 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에 응답하여 반복 할 수는 있지만 연속적으로 할 수는 없습니다 . (확실히 배열이 필요합니다)
빠른 Google 검색 으로 자바 스크립트에서 해시 테이블이 나타납니다.
해시에서 값을 반복하는 예제 코드 (위에서 언급 한 링크에서) :
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 행 : 항상 당신의 평등 주위에 공간이 있으면 괜찮습니다.
trim
1 행 에없는 것이 좋습니다.=
각 키를 사용 하고 자릅니다. -
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을 지원합니다 . 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을 사용하십시오 .
답변
방금 이렇게 만들면 좋을 것 같아요
var arr = [];
arr = {
key1: 'value1',
key2:'value2'
};
더 많은 정보를 원하시면, 이것을보십시오
