如果有JavaScript对象:

var objects={...};

假设,它有超过50个属性,不知道属性名称(即不知道“键”)如何在循环中获得每个属性值?


当前回答

var objects={...}; this.getAllvalues = function () {
        var vls = [];
        for (var key in objects) {
            vls.push(objects[key]);
        }
        return vls;
    }

其他回答

对于那些早期适应CofeeScript时代的人来说,这里有另一个等价的东西。

val for key,val of objects

这可能比这样更好,因为可以减少对象,重新键入,降低可读性。

objects[key] for key of objects

在ECMAScript5中使用

 keys = Object.keys(object);

否则,如果您的浏览器不支持它,请使用众所周知的for. in循环

for (key in object) {
    // your code here
}

你可以循环遍历键:

foo = {one:1, two:2, three:3};
for (key in foo){
    console.log("foo["+ key +"]="+ foo[key]);
}

将输出:

foo[one]=1
foo[two]=2
foo[three]=3
const object1 = {
  a: 'somestring',
  b: 42
};

for (let [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed

下面是一个类似于PHP的array_values()函数

function array_values(input) {
  var output = [], key = '';
  for ( key in input ) { output[output.length] = input[key]; }
  return output;
}

如果你使用ES6或更高版本,下面是如何获取对象的值:

Array.from(values(obj));