簡體   English   中英

選擇數組中的項目-Javascript-使用篩選方法

[英]Selecting Items in array - Javascript - Using Filter method

今天有人問一個問題,要弄清楚從I到數組末尾選擇數組中的某些元素,這讓我想知道如何使用filter方法。

有人提供的解決方案之一是使用slice而且我了解您可以在索引之間進行選擇,但是您將如何實現filter方法來做同樣的事情?

 let arr = ['bug', 'cat', 'dog', 'flea', 'bat', 'hat', 'rat']; let newArr = arr.filter(element => element >= element.indexOf(3)); console.log(newArr); 

這是我想出的方法,它不起作用,但是我們的想法是選擇索引為3或更大的所有字符串,然后將它們返回到另一個數組中。

運行時將索引傳遞給過濾器回調:

let newArr = arr.filter((element, index) => index >= 3);

在性能方面,您仍在制作一個新數組並復制值,因此它與.slice()大致相同。

當您訪問每個項目時,可以使用一個計數器並將其遞減直到計數器達到零。 然后取這個值。

 const fromIndex = i => _ => !i || !i--, array = ['bug', 'cat', 'dog', 'flea', 'bat', 'hat', 'rat'], result = array.filter(fromIndex(3)); console.log(result); 

您應該使用過濾條件創建一個函數:

let arr = ['bug', 'cat', 'dog', 'flea', 'bat', 'hat', 'rat'];

function filterCriteria(item) {
  return item >= someValue;
}

function someFunction() {
  return arr.filter(filterCriteria);
}

“ someFunction”將返回過濾后的數組

過濾器回調中的第二個參數是索引。 所以你可以做這樣的事情

arr.filter((element,index)=>索引> = 3);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM