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"
。
答案 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);