简体   繁体   English

如何按索引范围的顺序删除数组元素?

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

I have an array:我有一个数组:

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

I want to show elements only in a certain range of array indexes.我只想显示特定范围的数组索引中的元素。 For example: how to show everything between array index 1 (-22.50$) and array index 3 (+22.50$)?例如:如何显示数组索引 1 (-22.50$) 和数组索引 3 (+22.50$) 之间的所有内容? All elements with lower or higher indexes should be removed.应删除所有具有较低或较高索引的元素。

There are many ways to do so:有很多方法可以做到:

slice (returns new array)切片(返回新数组)

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

splice (modifies array) splice(修改数组)

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


...plus many other more complicated techniques including but not limited to: ...加上许多其他更复杂的技术,包括但不限于:

filter (returns new array)过滤器(返回新数组)

in this case it's effectively just a .slice .在这种情况下,它实际上只是一个.slice

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

You can use the filter method of an array.您可以使用数组的 filter 方法。
Here is the code snippet.这是代码片段。
The newArray will hold the value you required. 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