问题描述
我目前正在用 JavaScript 做一个项目,该项目涉及从字符串数组(如数组“greetings”)中删除某些标点符号。我使用迭代器遍历数组中的每个项目,然后我编写了一个循环来遍历当前项目中的每个字母。我声明了一个空变量,用于根据字母不是双引号、句点或感叹号来连接每个字母。然后在循环遍历单词中的所有字母后,我将最终连接的字符串返回到映射迭代器中。当我尝试打印 nopunctGreetings 时,我得到空字符串。
const greetings = ['Hi,','my','name','is','Dave!']
const nopunctGreetings = greetings.map(word => {
let concatedWord = '';
for (let i = 0; i < word.length; i++) {
if (word[i] != '"' || word[i] != '.' || word[i] != '!') {
concatedWord.concat(word[i].toLowerCase());
}
}
return concatedWord;
})
console.log(nopunctGreetings)
>>> ['','','']
如果有其他更简洁的方法可以做到这一点,请告诉我。
解决方法
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat
concat() 方法将字符串参数连接到调用字符串并返回一个新字符串。
所以你需要做
concatedWord = concatedWord.concat(word[i].toLowerCase());
此外,您还需要:
word[i] != '"' && word[i] != '.' && word[i] != '!'
而不是 ||
,因为 word[i]
将始终不是 "
或不是 .
const greetings = ['Hi,','my','name','is','Dave!']
const noPunctGreetings = greetings.map(word => {
let concatedWord = '';
for (let i = 0; i < word.length; i++) {
if (word[i] != '"' && word[i] != '.' && word[i] != '!') {
concatedWord = concatedWord.concat(word[i].toLowerCase());
}
}
return concatedWord;
})
console.log(noPunctGreetings)
或者,更简单:
const greetings = ['Hi,'Dave!']
const noPunctGreetings = greetings.map(word => word.replace(/[."!]/g,"").toLowerCase())
console.log(noPunctGreetings)