I am trying to understand the concept of KeyValue pair list in JavaScript.
Do I have to use an array? I tried adding this data to an array:
key: 1, value: "apple"
key: 2, value: "banana"
key: 7, value: "cherry"
key: 24, value: "grapes"
But how do I get the value of key 7 without using loop?
I create JSFiddle with an example. How can I edit this example to return me the value of the key? At the moment it is returning a value of the first entered keyValue pair.
Don’t make your “dict” a list of key/value pairs. Instead, use an object which gives you all the functionality automatically:
var dict = {}; // object literal
function addToList() {
var aKey = document.getElementById("fkey").value;
var aValue = document.getElementById("fvalue").value;
dict[aKey] = aValue;
}
function getFromList() {
var aKey = document.getElementById("rkey").value;
document.getElementById("rvalue").value = dict[aKey];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句