在JavaScript中循环对象

时间:2013-10-22 05:35:20

标签: javascript

我有像

这样的对象
{ a: 2.078467321618,
  b :13521.4,
  c : 4503.9,
  more...}

(在调试模式下)

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

8 个答案:

答案 0 :(得分:1)

Object.keys(obj).forEach(function(key) {
    var val = obj[key];
    ...
});

答案 1 :(得分:1)

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

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

注意:这里我们检查密钥是否属于我们的对象,但是不是通过hasOwnProperty方法的原型。

答案 2 :(得分:0)

Try the following:

for(var key in object){
    var value = object[key];
    //now you have access to "key" and "value"
}

答案 3 :(得分:0)

尝试这样的事情

for(var key in object){
    alert(key);// will give key
    alert(object[key]);// will give value
}

答案 4 :(得分:0)

实际上非常简单:

for (var key in object) {
   // do something with object[key]
}

答案 5 :(得分:0)

试试这个

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

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

结果是sum = 5 + 10 + 15

答案 6 :(得分: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);

答案 7 :(得分: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/