gpt4 book ai didi

javascript函数搜索对象属性并返回值

转载 作者:行者123 更新时间:2023-12-03 00:41:28 26 4
gpt4 key购买 nike

我有一个字符串: constphrase =“森林里有一只蓝色的鸟”;

和一个对象:

const color = {
'blue': 20,
'red': 10,
'yellow': 5
};

我想编写一个 Javascript 函数来检查字符串是否包含颜色对象的任何属性,如果包含,则返回匹配属性的值,因此在上面的示例中,它将返回 20。

我正在使用 Lodash,但我不知道如何编写这个函数 (_.some, _.find?)

最佳答案

如果需要获取字符串中所有颜色的总和,可以使用 Array.reduce() (或 lodash 的 _.reduce() )。将短语更改为小写,用空格分隔,减少,并对颜色值求和(或其他单词为 0):

const color = {
'blue': 20,
'red': 10,
'yellow': 5
};

const getColorsValue = (p) =>
p.toLowerCase()
.split(/\s+/)
.reduce((s, w) => s + (color[w] || 0), 0);

console.log(getColorsValue('there is a blue bird in the forest')); // 20

console.log(getColorsValue('there is a blue bird in the red forest')); // 30

关于javascript函数搜索对象属性并返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53446083/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com