【问题标题】:How to check if the last characters in an array meet a condition如何检查数组中的最后一个字符是否满足条件
【发布时间】:2021-12-29 20:40:41
【问题描述】:
我试图删除数组中元素的最后一个字符,前提是它们满足条件。例如:如果它们以 s 结尾,那么我删除 s。如果不是,则元素应保持不变。
这就是我正在尝试的方式:
let myList = []
for (let i = 0; i < arrays.length; i++){
if (arrays[i].substring(arrays[i].length - 1) == 's'){
item = arrays[i].slice(0,-1);
myList.push(item);
}else{
myList.push(arrays[i]);
}
但它不起作用,你知道为什么吗?
【问题讨论】:
标签:
javascript
arrays
substring
【解决方案1】:
这边
const
arr = ['Johns','Paul', 'ringos', 'Georges']
, myList = arr.map( name => /s$/.test(name) ? name.slice(0, -1) : name)
;
console.log( myList )
【解决方案2】:
如果名字endsWiths那么你可以slice它为:
const arr = ["Johns", "Paul", "ringos", "Georges"];
const myList = arr.map(name => name.endsWith("s") ? name.slice(0, -1) : name);
console.log(myList);
【解决方案3】:
从您编写的代码来看,它似乎缺少}。如果你想知道为什么终端什么都没有发生,那是因为你没有在代码中写console.log(myList)。
这段代码应该可以工作:
const arrays = ['Apples', 'Oranges', 'Bananas', 'Pear']
let myList = []
for (let i = 0; i < arrays.length; i++){
if (arrays[i].substring(arrays[i].length - 1) == 's') {
item = arrays[i].slice(0,-1);
myList.push(item);
} else {
myList.push(arrays[i]);
}
}
console.log("List:", myList)