0

我有一个像

{ a: 2.078467321618,
  b :13521.4,
  c : 4503.9,
  more...}

(在调试模式下)

我想遍历对象并分离键和值;我怎样才能做到这一点?

4

8 回答 8

1
Object.keys(obj).forEach(function(key) {
    var val = obj[key];
    ...
});
于 2013-10-22T05:36:47.307 回答
1

另一种方法是通过 foreach 实现:

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        // do something with the key and obj[key], which is val
    }
}

注意:这里我们通过方法检查键是否属于我们的对象,而不是它的原型hasOwnProperty

于 2013-10-22T05:39:34.477 回答
0
Try the following:

for(var key in object){
    var value = object[key];
    //now you have access to "key" and "value"
}
于 2013-10-22T05:37:51.427 回答
0

尝试这样的事情

for(var key in object){
    alert(key);// will give key
    alert(object[key]);// will give value
}
于 2013-10-22T05:39:52.387 回答
0

其实很简单:

for (var key in object) {
   // do something with object[key]
}
于 2013-10-22T05:41:13.933 回答
0

尝试这个

var sum = 0;
var obj = {prop1: 5, prop2: 10, prop3: 15};

for each (var item in obj)
{
 sum += item;
}

结果是总和 = 5+10+15

于 2013-10-22T05:42:31.703 回答
0

试试下面的代码:

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);
于 2013-10-22T05:45:41.613 回答
0

使用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/

于 2013-10-22T06:04:58.790 回答