how to remove elements of array?

前端 未结 4 1410
情话喂你
情话喂你 2020-12-29 20:04

Is it possible to remove the contents of the array based on the index? If I have 2 arrays like these:

Array1 that contains 15 values and I want to get the last 10 va

相关标签:
4条回答
  • 2020-12-29 20:20

    To keep the first ten items:

    if (theArray.length > 10) theArray = theArray.slice(0, 10);
    

    or, perhaps less intuitive:

    if (theArray.length > 10) theArray.length = 10;
    

    To keep the last ten items:

    if (theArray.length > 10) theArray = theArray.slice(theArray.length - 10, 10);
    

    You can use a negative value for the first parameter to specify length - n, and omitting the second parameter gets all items to the end, so the same can also be written as:

    if (theArray.length > 10) theArray = theArray.slice(-10);
    

    The splice method is used to remove items and replace with other items, but if you specify no new items it can be used to only remove items. To keep the first ten items:

    if (theArray.length > 10) theArray.splice(10, theArray.length - 10);
    

    To keep the last ten items:

    if (theArray.length > 10) theArray.splice(0, theArray.length - 10);
    
    0 讨论(0)
  • 2020-12-29 20:22

    Use the function array.splice(index, count) to remove count elements at index. To remove elements from the end, use array1.splice(array1.length - 10, 1);

    0 讨论(0)
  • 2020-12-29 20:23

    See splice()

    The splice() method changes the content of an array by removing existing elements and/or adding new elements.

    It won't create a new array, if you want to create new array use slice.

    0 讨论(0)
  • 2020-12-29 20:27

    Kind of hard to follow your question, but try these:

    array = array.slice(-10);
    
    // or
    
    last10 = array.splice(-10);
    // array has first array.length-10 elements
    
    0 讨论(0)
提交回复
热议问题