简体   繁体   English

在 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"];

I need every element that ends with berry to be deleted.我需要删除所有以berry结尾的元素。 The array should end up like this:数组应该像这样结束:

var arr = ["apple"]; 

You can user Array.prototype.filter to create a new, filtered array:您可以使用Array.prototype.filter创建一个新的、过滤的数组:

var newArr = arr.filter(function(arrayElement){
    return arrayElement.indexOf("berry") != arrayElement.length - "berry".length;
});

From the docs:从文档:

The filter() method creates a new array with all elements that pass the test implemented by the provided function. filter() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

So, the provided callback should return true to project the element into the output array, or false to omit it.因此,提供的回调应该返回true以将元素投影到输出数组中,或者返回false以省略它。 How you might implement the test is down to you.您如何实施测试取决于您。 The test I provide is somewhat naive.我提供的测试有点幼稚。

To find items that ends with something we use something$ (the $ indicates the end of string or end of line).要查找以某物结尾的项目,我们使用something$$表示字符串的结尾或行的结尾)。 If we negate this regex expression we can find items that not ending with that string.如果我们否定这个regex表达式,我们可以找到不以该字符串结尾的项目。
On other hand, arrays in javascript have a filter function that filters the array items based on a filtering function.另一方面,javascript 中的数组有一个filter函数,它根据filter函数过滤数组项。 By combining this two we can create a new array just containing what we want.通过将这两者结合起来,我们可以创建一个仅包含我们想要的内容的新数组。

 var arr = ["strawberry", "apple", "blueberry"]; var endsWith = "berry" var regx = new RegExp(endsWith+"$"); var result = arr.filter(function(item){return !regx.test(item);}) alert(result);

You can do it using Array.prototype.filter() combined with String.prototype.endsWith() :你可以使用Array.prototype.filter()String.prototype.endsWith()

// Declaring array of fruits
let arr = ['strawberry', 'apple', 'blueberry'];

// Filtering elements that are not ending with 'berry'
let filtered = arr.filter(fruit => !fruit.endsWith('berry'));

console.log(filtered);
// ['apple']
var fruits = ["strawberry", "apple", "blueberry"];
for(var i=0;i<3;i++){
var a = fruits[i].indexOf("berry") > -1;
    document.getElementById("demo").innerHTML = a;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM