如果有JavaScript对象:

var objects={...};

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


当前回答

下面是一个类似于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));

其他回答

这个问题没有指定是否也需要继承的和不可枚举的属性。

获得谷歌不容易找到的所有东西,包括继承的属性和不可枚举的属性,都存在一个问题。

如果我们要获得所有继承的和不可枚举的属性,我的解决方案是:

function getAllPropertyNames(obj) {
    let result = new Set();
    while (obj) {
        Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
        obj = Object.getPrototypeOf(obj);
    }
    return [...result];
}

然后遍历它们,只需要使用for-of循环:

函数getAllPropertyNames(obj) { let result = new Set(); While (obj) { Object.getOwnPropertyNames (obj)。forEach(p => result.add(p)); obj = Object.getPrototypeOf(obj); } 返回结果[…]; } 让obj = { 美国广播公司(abc): 123, 某某:1.234, foobar:“你好” }; for (p of getAllPropertyNames(obj)) console.log(p);

在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

使用像这样的填充材料:

if(!Object.values){Object.values=obj=>Object.keys(obj).map(key=>obj[key])}

然后使用

Object.values(my_object)

3)利润!

下面是一个类似于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));