我正在检查数组中是否存在某个值,如果存在,我想分配一个特定于 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 - 检查数组中是否存在值,如果为 true 则分配一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49953892/