Deleting array elements in JavaScript - delete vs splice

后端 未结 27 4207
予麋鹿
予麋鹿 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:25

    delete Vs splice

    when you delete an item from an array

    var arr = [1,2,3,4]; delete arr[2]; //result [1, 2, 3:, 4]
    console.log(arr)

    when you splice

    var arr = [1,2,3,4]; arr.splice(1,1); //result [1, 3, 4]
    console.log(arr);

    in case of delete the element is deleted but the index remains empty

    while in case of splice element is deleted and the index of rest elements is reduced accordingly

提交回复
热议问题