我正在处理 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]);
}
最佳答案
您可以使用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
关于javascript - 编写一个函数,将对象数组作为参数并返回对象名称数组。然后,将该数组记录到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43239682/