Deleting array elements in JavaScript - delete vs splice

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

    Others have already properly compared delete with splice.

    Another interesting comparison is delete versus undefined: a deleted array item uses less memory than one that is just set to undefined;

    For example, this code will not finish:

    let y = 1;
    let ary = [];
    console.log("Fatal Error Coming Soon");
    while (y < 4294967295)
    {
        ary.push(y);
        ary[y] = undefined;
        y += 1;
    }
    console(ary.length);
    

    It produces this error:

    FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.
    

    So, as you can see undefined actually takes up heap memory.

    However, if you also delete the ary-item (instead of just setting it to undefined), the code will slowly finish:

    let x = 1;
    let ary = [];
    console.log("This will take a while, but it will eventually finish successfully.");
    while (x < 4294967295)
    {
        ary.push(x);
        ary[x] = undefined;
        delete ary[x];
        x += 1;
    }
    console.log(`Success, array-length: ${ary.length}.`);
    

    These are extreme examples, but they make a point about delete that I haven't seen anyone mention anywhere.

提交回复
热议问题