删除以JavaScript中某些字符串结尾的数组元素 [英] Delete elements of array that end with certain strings in JavaScript
问题描述
我有一个数组,我需要删除以某个字符串结尾的每个元素.
I have an array and I need every element that ends with a certain string to be deleted.
var arr = ["strawberry", "apple", "blueberry"];
我需要删除所有以 berry 结尾的元素.该数组应以如下形式结束:
I need every element that ends with berry to be deleted. The array should end up like this:
var arr = ["apple"];
推荐答案
You can user Array.prototype.filter to create a new, filtered array:
var newArr = arr.filter(function(arrayElement){
return arrayElement.indexOf("berry") != arrayElement.length - "berry".length;
});
从文档中
filter()方法创建一个新数组,其中包含所有通过提供的功能实现的测试的元素.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
因此,提供的回调应返回true
将该元素投影到输出数组中,或返回false
将该元素省略.您如何实施测试取决于您.我提供的测试有些天真.
So, the provided callback should return true
to project the element into the output array, or false
to omit it. How you might implement the test is down to you. The test I provide is somewhat naive.
这篇关于删除以JavaScript中某些字符串结尾的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!