假设您有一个对象数组。
let dogs = [
{
colour: "blue",
breed: "poodle"
},
{
colour: "yellow",
breed: "poodle"
},
{
colour: "red",
breed: "laborator"
}
];
按品种匹配时如何获得颜色?
我尝试过:
let myFavouriteColour = dogs.find(dog => {
if (dog.breed === "laborator") return dog.colour
});
这将返回一个符合以上条件的对象;我只希望它返回colour
属性中的值。
答案 0 :(得分:2)
一旦.find
匹配,返回true
(或仅返回相等测试),然后访问.find
之外的匹配对象的属性:
let dogs = [
{
colour: "blue",
breed: "poodle"
},
{
colour: "yellow",
breed: "poodle"
},
{
colour: "red",
breed: "laborator"
}
];
const laborator = dogs.find(dog => dog.breed === "laborator");
if (laborator) {
const myFavouriteColour = laborator.colour;
console.log(myFavouriteColour);
}
答案 1 :(得分:1)
Array.find()
是JavaScript中的内置函数,用于获取 第一个元素 中的对象(或值,如果它是值的数组)满足提供条件的数组。您可以访问返回结果的属性。
let dogs = [
{
colour: "blue",
breed: "poodle"
},
{
colour: "yellow",
breed: "poodle"
},
{
colour: "red",
breed: "laborator"
}
];
let myFavouriteColour = dogs.find(dog => dog.breed === "laborator").colour;
console.log(myFavouriteColour);