【发布时间】:2020-06-23 22:05:30
【问题描述】:
我是软件开发的新手并且一直在上课,我在找出如何根据第二个参数字符删除数组中的项目时遇到问题
编写一个带有 2 个参数的函数“removeWordsWithChar”:
- 字符串数组
- 长度为 1 的字符串(即:单个字符) 它应该返回一个新数组,其中包含第一个参数中的所有项目,但第二个参数中包含字符的项目除外(不区分大小写)。
例子:
----removeWordsWithChar(['aaa', 'bbb', 'ccc'], 'b') --> ['aaa', 'ccc']
----removeWordsWithChar(['pizza', 'beer', 'cheese'], 'E') --> ['pizza']
function removeWordsWithChar(arrString, stringLength) {
const arr2 = [];
for (let i = 0; i < arrString.length; i++) {
const thisWord = arrString[i];
if (thisWord.indexOf(stringLength) === -1) {
arr2.push(thisWord);
}
}
return arr2;
}
【问题讨论】:
-
Array.prototype.filter
arr2.filter(x=>!x.toLowerCase().includes(strLength.toLowerCase())) -
不区分大小写,所以使用
if (thisWord.toLowerCase().indexOf(stringLength.toLowerCase()) === -1) -
成功了!我不敢相信我错过了小写字母。谢谢!
-
你也可以使用localeCompare developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript arrays loops