给定以下数组,如何编写ES6表达式以返回所有名字

时间:2017-11-30 00:53:27

标签: javascript arrays ecmascript-6

const ducks = [
   { first: 'Stan', last: 'duck' },
   { first: 'Steve', last: 'duck' },
   { first: 'Kyle', last: 'duck' },
];

我试过

const ducks = [
  { first: 'Stan', last: 'duck' },
  { first: 'Steve', last: 'duck' },
  { first: 'Kyle', last: 'duck' },
];

console.log(ducks, [3]); 

这太过分了:

[...]                                     [3]
  0: {first: "Stan", last: "duck"}          0: 3
  1: {first: "Steve", last: "duck"}         length: 1
  2: {first: "Kyle", last: "duck"}          __proto__: Array(0)
  length: 3
  __proto__: Array(0)

需要它只返回名称"Stan""Steve""Kyle"

2 个答案:

答案 0 :(得分:8)

您只是记录数组和另一个包含数字3的数组。您的代码与此相同(虽然在控制台的两行中分开):

console.log(ducks);
console.log([3]);

您应该使用map函数来获取所有名字的数组,如:

let firstNames = ducks.map(duck => duck.first);
console.log(firstNames);

如果您只想记录名称,请使用forEach,如下所示:

ducks.forEach(duck => console.log(duck.first));

答案 1 :(得分:4)

使用数组map(),如下所示:

const ducks = [
    { first: 'Stan', last: 'duck' },
    { first: 'Steve', last: 'duck' },
    { first: 'Kyle', last: 'duck' }
];
 
let res = ducks.map((item) => item.first);
 
console.log(res);