下面的代码很实用,但我想重构!==允许我的三元只能在非空白的值上运行的部分,因此我可以包括边缘用例测试.这将包括任何非字母值以及空白,我知道regex可能起到一定作用,但我找不到一种巧妙的方法将其合并到三元操作之前的if()语句中.
const letterPositions = function(strPos) {
if (typeof strPos !== 'string') {
return console.log('Sorry your input is not a string');
}
const result = {};
for (let i = 0; i < strPos.length; i++) {
if (strPos[i] !== ' ') {
result[strPos[i]] ? result[strPos[i]].push(i) : (result[strPos[i]] = [i]);
}
}
return result;
};
console.log(letterPositions('aa bb cc'));