gpt4 book ai didi

javascript - JS - 检查数组中是否存在一个值,如果为真则赋值

转载 作者:行者123 更新时间:2023-11-29 20:54:34 25 4
gpt4 key购买 nike

我正在检查数组中是否存在某个值,如果存在,我想分配一个特定于 myArray 中的值的值。下面的代码有效,但有很多重复。有更好的做事方式吗?

const myArray = ['a', 'b', 'c', 'd'];
const aExists = myArray.indexOf('a') > -1;
const bExists = myArray.indexOf('b') > -1;
const cExists = myArray.indexOf('c') > -1;

return [
(aExists ? 'value-for-a' : undefined),
(bExists ? 'or-something-for-b' : undefined),
(cExists ? 'different-value-for-c' : undefined)
].filter(x => x !== undefined).toString();

最佳答案

创建键/值字典 (dict)。使用 Object.keys() ,并用 Array.reduce() 迭代键.使用 Array.includes() 查找 myArray 中是否存在键,并将 dict 中的匹配键添加到结果中:

const dict = {
'a': 'value-for-a',
'b': 'or-something-for-b',
'c': 'different-value-for-c'
};
const myArray = ['a', 'b', 'c', 'd'];

const result = Object.keys(dict)
.reduce((r, k) => {
if(myArray.includes(k)) r.push(dict[k]);

return r;
}, []);

console.log(result);

关于javascript - JS - 检查数组中是否存在一个值,如果为真则赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49953892/

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