说我有一个像这样的字符串数组:
var someArray = ['this is something', 'this is something else', "this ain't something"];
我想过滤它们以this is
开头的字符串,同时还要除去过滤数组中的this is
。我目前正在通过写:
var newArray = [];
for (var index = 0; index < someArray.length; index++) {
if (someArray [index].startsWith ("this is ")) {
newArray.push (someArray [index].slice (8));
}
}
我可以做的另一种方法是编写类似以下内容的
function filterByThisIs (arrayElement) {
return arrayElement.startsWith ("this is ");
}
function removeThisIs (arrayElement, index, someOtherArray) {
someOtherArray [index] = arrayElement.slice (8);
}
var newArray = someArray.filter (filterByThisIs).forEach (removeThisIs);
现在,也许只是因为我是JavaScript新手并且刚刚发现array.filter()
,但是我觉得array.filter()
应该能够在没有{{1}的帮助下进行类似的操作},因为它仍然接受函数参数。 array.forEach()
可以在将元素过滤到新数组时以某种方式为我操纵这些元素吗?还是我可能没有想到的比上述更简单,更清洁的方法?
答案 0 :(得分:2)
您可以使用reduce
:
var newArray = someArray.reduce((a, c) => {
if (!c.startsWith("this is ")) return a;
a.push(c.slice(8));
return a;
}, []);
答案 1 :(得分:2)
Array.filter()可以在将元素返回到新数组之前对其进行操作吗?
不,它不操纵元素。它只是返回一个带有通过条件的元素的新数组。
但是有很多方法可以做您想要的。一种方法是将Array.filter()与Array.map()结合使用:
var someArray = ['this is something', 'this is something else', "this ain't something"];
// Filter array items which start with "this is ".
var filteredArray = someArray.filter(element => element.startsWith("this is "));
// Trim "this is " from each item.
var outputArray = filteredArray.map(element => element.slice(8));
console.log(outputArray);
答案 2 :(得分:0)
正如其他人所说,有很多方法可以实现这一目标,这是我的方法,
var someArray = ['this is something', 'this is something else', "this ain't something"];
// First filter item and then slice that text on returning item
var newArray = someArray
.filter(item => item.startsWith("this is "))
.map(item => item.slice(8));
console.log(newArray);