编写一个函数,返回它对应的所有键的所有值的数组

时间:2016-11-08 12:00:37

标签: javascript arrays function object

我想创建一个可以调用的函数来返回一个包含每个对象的所有值的数组。 e.g. function find ("firstName") returns ["Virginia", "Zadie", "Jane", "Bell"]

解释也会很棒,因为我对编程和尝试学习都非常新。谢谢

var writers = [
  {
    firstName: "Virginia",
    lastName: "Woolf",
    occupation: "writer",
    age: 59,
    alive: false
  },
  {
    firstName: "Zadie",
    lastName: "Smith",
    occupation: "writer",
    age: 41,
    alive: true
  },
  {
    firstName: "Jane",
    lastName: "Austen",
    occupation: "writer",
    age: 41,
    alive: false
  },
  {
    firstName: "bell",
    lastName: "hooks",
    occupation: "writer",
    age: 64,
    alive: true
  },
];

2 个答案:

答案 0 :(得分:1)

您可以使用map()方法创建此功能。

var writers = [ { firstName: "Virginia", lastName: "Woolf", occupation: "writer", age: 59, alive: false }, { firstName: "Zadie", lastName: "Smith", occupation: "writer", age: 41, alive: true }, { firstName: "Jane", lastName: "Austen", occupation: "writer", age: 41, alive: false }, { firstName: "bell", lastName: "hooks", occupation: "writer", age: 64, alive: true }];

function get(key, arr) {
  return arr.map(function(e) {
    return e[key]
  })
}

console.log(get('firstName', writers))
console.log(get('occupation', writers))

答案 1 :(得分:0)

您可以使用该键作为查找功能的参数。

property accessor,此处使用的是括号表示法。

keys= 'name';
variable[key]

这与相同,写成点符号

variable.name



function find (key) {
    return writers.map(function (a) { 
        return a[key];
    });
}

var writers = [ { firstName: "Virginia", lastName: "Woolf", occupation: "writer", age: 59, alive: false }, { firstName: "Zadie", lastName: "Smith", occupation: "writer", age: 41, alive: true }, { firstName: "Jane", lastName: "Austen", occupation: "writer", age: 41, alive: false }, { firstName: "bell", lastName: "hooks", occupation: "writer", age: 64, alive: true }, ];
               
console.log(find('firstName'));
console.log(find('lastName'));