El *_* CC 2 javascript if-statement
是否有更短的更有效的方法来做到这一点?它似乎有点沉重,我只是想知道它是否可以浓缩?
var y = []
for(let i=0;i < word.length;++i){
if(word[i] == "A"|| word[i] == "a"){
y.push(0)
}
else if(word[i] == "B"|| word[i] == "b"){
y.push(1);
}
else if(word[i] == "C"|| word[i] == "c"){
y.push(2);
}
else if(word[i] == "D"|| word[i] == "d"){
y.push(3);
}
and so on..
return(y);
}
Run Code Online (Sandbox Code Playgroud)
一种选择是使用一个字符数组,然后.indexOf用来查找字符的索引:
const word = 'bBac';
const chars = ['a', 'b', 'c', 'd'];
const y = [...word].map(char => chars.indexOf(char.toLowerCase()))
console.log(y);
// return y;Run Code Online (Sandbox Code Playgroud)
为了更好的效率,而不是.indexOf(即O(N)),使用a Map(O(1)):
const word = 'bBac';
const charMap = new Map([
['a', 0],
['b', 1],
['c', 2],
['d', 3]
]);
const y = [...word].map(char => charMap.get(char.toLowerCase()))
console.log(y);
// return y;Run Code Online (Sandbox Code Playgroud)