我有一个像
{ a: 2.078467321618,
b :13521.4,
c : 4503.9,
more...}
(在调试模式下)
我想遍历对象并分离键和值;我怎样才能做到这一点?
我有一个像
{ a: 2.078467321618,
b :13521.4,
c : 4503.9,
more...}
(在调试模式下)
我想遍历对象并分离键和值;我怎样才能做到这一点?
Object.keys(obj).forEach(function(key) {
var val = obj[key];
...
});
另一种方法是通过 foreach 实现:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
// do something with the key and obj[key], which is val
}
}
注意:这里我们通过方法检查键是否属于我们的对象,而不是它的原型hasOwnProperty
。
Try the following:
for(var key in object){
var value = object[key];
//now you have access to "key" and "value"
}
尝试这样的事情
for(var key in object){
alert(key);// will give key
alert(object[key]);// will give value
}
其实很简单:
for (var key in object) {
// do something with object[key]
}
尝试这个
var sum = 0;
var obj = {prop1: 5, prop2: 10, prop3: 15};
for each (var item in obj)
{
sum += item;
}
结果是总和 = 5+10+15
试试下面的代码:
var keys=Array();
var values = Array();
for (var key in obj) {
//has own property is checked to bypass inherited properties like prototype
if (obj.hasOwnProperty(key)) {
keys.push(key)';
values.push(obj[key]);
}
}
//以下是分开的键和值,对它们做任何你想做的事情
console.log(keys);
console.log(values);
使用jQuery:
var obj = { a: 2.078467321618, b :13521.4, c : 4503.9 };
var keyArr = [];
var valArr = [];
//iterate obj
$.each(obj, function(k, v) {
//add items to the keyArr from obj's keys.
keyArr.push(k);
//add items to the varArr from obj's keys.
valArr.push(v);
});
//show the result
alert(keyArr);
alert(valArr);
看演示:http: //jsfiddle.net/bauangsta/KdZrA/