在javascript中存储key=>值数组的最佳方法是什么,以及如何通过循环?
每个元素的键应该是一个标记,比如{id}或者仅仅是id,值应该是id的数值。
它应该是一个现有javascript类的元素,或者是一个全局变量,可以很容易地通过类引用。
可以使用jQuery。
在javascript中存储key=>值数组的最佳方法是什么,以及如何通过循环?
每个元素的键应该是一个标记,比如{id}或者仅仅是id,值应该是id的数值。
它应该是一个现有javascript类的元素,或者是一个全局变量,可以很容易地通过类引用。
可以使用jQuery。
当前回答
如果我没理解错的话:
var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;
var sum = 0;
for (var name in hash) {
sum += hash[name];
}
alert(sum); // 579
其他回答
如果我没理解错的话:
var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;
var sum = 0;
for (var name in hash) {
sum += hash[name];
}
alert(sum); // 579
简单地这样做
var key = "keyOne";
var obj = {};
obj[key] = someValue;
你可以使用地图。
JavaScript ES6中引入了一种新的数据结构。 用于存储键/值对的JavaScript对象的替代方案。 具有用于键/值对迭代的有用方法。
var map = new Map();
map.set('name', 'John');
map.set('id', 11);
// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }
使用键获取Map的值
console.log(map.get('name')); // John
console.log(map.get('id')); // 11
获取地图的大小
console.log(map.size); // 2
检查键在映射中存在
console.log(map.has('name')); // true
console.log(map.has('age')); // false
得到钥匙
console.log(map.keys()); // MapIterator { 'name', 'id' }
得到值
console.log(map.values()); // MapIterator { 'John', 11 }
获取Map的元素
for (let element of map) {
console.log(element);
}
// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]
打印键值对
for (let [key, value] of map) {
console.log(key + " - " + value);
}
// Output:
// name - John
// id - 11
只打印Map的键
for (let key of map.keys()) {
console.log(key);
}
// Output:
// name
// id
只打印Map的值
for (let value of map.values()) {
console.log(value);
}
// Output:
// John
// 11
这就是JavaScript对象的含义:
var myArray = {id1: 100, id2: 200, "tag with spaces": 300};
myArray.id3 = 400;
myArray["id4"] = 500;
你可以使用for..in循环遍历它:
for (var key in myArray) {
console.log("key " + key + " has value " + myArray[key]);
}
请参见:使用对象(MDN)。
在ECMAScript6中也有Map(参见浏览器兼容性表):
Object有一个原型,所以映射中有默认键。从ES5开始,可以通过使用map = Object.create(null)来绕过这一点,但很少这样做。 对象的键是字符串和符号,它们可以是Map的任何值。 您可以很容易地获得Map的大小,而必须手动跟踪对象的大小。
数组中的对象:
var cars = [
{ "id": 1, brand: "Ferrari" }
, { "id": 2, brand: "Lotus" }
, { "id": 3, brand: "Lamborghini" }
];