Deleting array elements in JavaScript - delete vs splice

后端 未结 27 3602
予麋鹿
予麋鹿 2020-11-21 05:31

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method?

For example:

myArray = [\         


        
27条回答
  •  礼貌的吻别
    2020-11-21 06:13

    OK, imagine we have this array below:

    const arr = [1, 2, 3, 4, 5];
    

    Let's do delete first:

    delete arr[1];
    

    and this is the result:

    [1, empty, 3, 4, 5];
    

    empty! and let's get it:

    arr[1]; //undefined
    

    So means just the value deleted and it's undefined now, so length is the same, also it will return true...

    Let's reset our array and do it with splice this time:

    arr.splice(1, 1);
    

    and this is the result this time:

    [1, 3, 4, 5];
    

    As you see the array length changed and arr[1] is 3 now...

    Also this will return the deleted item in an Array which is [3] in this case...

提交回复
热议问题