有其他解决方案吗?

时间:2020-09-21 03:37:49

标签: javascript

> let fullInteger = '';

const sentenceText = 'junayed';

for (let i = 0; i < sentenceText.length; i++) {
    if (sentenceText[i] == 'n' & sentenceText[i + 1] == 'a') {
        let newChar = sentenceText[i]
        newChar = 'a';
        fullInteger = fullInteger + newChar;
      
    }
    else if (sentenceText[i] == 'a' & sentenceText[i - 1] == 'n') {
        let newChar = sentenceText[i]
        newChar = 'n';
        fullInteger = fullInteger + newChar;
        
    }
    else{
        fullInteger = fullInteger + sentenceText[i];
    }
}
console.log(fullInteger);

如果找到“ na”到“ an”,它将采用一个字符串并将其更改。你们中有人知道我该如何缩短它,或者有其他选择吗?

2 个答案:

答案 0 :(得分:1)

这应该是一个简单的替换

const sentenceText = 'junayed';
const sentenceText1 = 'junyed';

function replaceContent(sentence){
  return sentence.replace(/na/g,'an');
}


console.log(replaceContent(sentenceText));// gives "juanyed" - ie: 'na' has been replaced by 'an'

console.log(replaceContent(sentenceText1));// gives junyed - ie: no 'na' to be replaced

答案 1 :(得分:1)

有很多方法可以实现这一目标。首先让我们尝试使用您的算法:

改进:

  • GetSet的建议,
    • &&而非&&表示按位与,双精度&&表示逻辑与。
    • i-1i+1上的错误:如果字符串以a开头或以n结尾,则代码将中断。您应该为其添加支票。您可以这样:
!!sentanceText[index]

其他建议

  • 您不需要多次分配。您的第二个任务使第一个任务无效。
let newChar = sentenceText[i]
newChar = 'a';
  • 如果是这种情况,则不需要其他。由于您已经检查了[i] === 'n' && [i+1] === 'a',因此只需设置newChar = 'an'并跳过下一个迭代即可。您可以通过增加i
if (sentenceText[i] == 'n' && sentenceText[i + 1] == 'a') {
  fullInteger = fullInteger + 'an';
  i++;
}

以下为示例

function getProcessedStr(sentenceText) {
  let fullInteger = '';
  for (let i = 0; i < sentenceText.length; i++) {
    if (sentenceText[i] === 'n' && !!sentenceText[i + 1] && sentenceText[i + 1] === 'a') {
      fullInteger = fullInteger + 'an';
      i++
    } else {
      fullInteger = fullInteger + sentenceText[i];
    }
  }
  console.log(fullInteger);
  return fullInteger
}

getProcessedStr('junayed');
getProcessedStr('junayedn');

参考文献: