簡體   English   中英

如何按索引范圍的順序刪除數組元素?

[英]How to remove elements of array in order of index range?

我有一個數組:

const savings = ["+10$", "-22.50$", "+5$", "+22.40$", "-3.5$"]; 

我只想顯示特定范圍的數組索引中的元素。 例如:如何顯示數組索引 1 (-22.50$) 和數組索引 3 (+22.50$) 之間的所有內容? 應刪除所有具有較低或較高索引的元素。

有很多方法可以做到:

切片(返回新數組)

savings.slice(1,4) // ['-22.50$', '+5$', '+22.40$']

splice(修改數組)

savings.splice(1,3) // ['-22.50$', '+5$', '+22.40$']


...加上許多其他更復雜的技術,包括但不限於:

過濾器(返回新數組)

在這種情況下,它實際上只是一個.slice

// ['-22.50$', '+5$', '+22.40$']
savings.filter((price, index) => index >= 1 && index <= 4)

您可以使用數組的 filter 方法。
這是代碼片段。
newArray將保存您需要的值。

const savings = ["+10$", "-22.50$", "+5$", "+22.40$", "-3.5$"];
const newArray = savings.filter((value, index, array) => {
    num = parseFloat(value.slice(0, value.length - 1)); // convert string into number to compare.
    min = parseFloat(array[1].slice(0, array[1].length - 1)); // convert string into number to compare.
    max = parseFloat(array[3].slice(0, array[3].length - 1)); // convert string into number to compare.

    if (value < min || value > max) { // check required condition
        return false;
    }

    return true;
});

暫無
暫無

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

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