我正在研究javascript数组,需要编写一个函数,该函数接受下面数组的第一个索引,并返回对象名称的数组。
var animals = [
{
name: 'murphy brown the dog',
type: 'dog',
age: 4,
fav_toy: 'squeaky octopus'
},
{
name: 'mervin',
type: 'cat',
age: 1,
fav_toy: 'catnip mouse'
},
{
name: 'peppercorn',
type: 'cat',
age: 3,
fav_toy: 'lady bug pillow'
},
{
name: 'willa',
type: 'cat',
age: 4,
fav_toy: 'jingle ball'
},
]
这是我的功能:
function getName(animals){
console.log(animals[0]);
return (animals[0]);
}
答案 0 :(得分:2)
您可以使用Array#map
仅返回每个对象的名称。
var animals = [{name:"murphy brown the dog",type:"dog",age:4,fav_toy:"squeaky octopus"},{name:"mervin",type:"cat",age:1,fav_toy:"catnip mouse"},{name:"peppercorn",type:"cat",age:3,fav_toy:"lady bug pillow"},{name:"willa",type:"cat",age:4,fav_toy:"jingle ball"}],
res = animals.map(v => v.name); // ---> return only the name value of each object
console.log(res); // ---> log the result to the console