Array.push return pushed value?

前端 未结 6 1910
盖世英雄少女心
盖世英雄少女心 2021-01-04 02:30

Are there any substantial reasons why modifying Array.push() to return the object pushed rather than the length of the new array might be a bad idea?

I

6条回答
  •  臣服心动
    2021-01-04 03:03

    See my detailed answer here

    TLDR;
    You can get the return value of the mutated array, when you instead add an element using array.concat[].

    concat is a way of "adding" or "joining" two arrays together. The awesome thing about this method, is that it has a return value of the resultant array, so it can be chained.

    newArray = oldArray.concat[newItem];

    This also allows you to chain functions together

    updatedArray = oldArray.filter((item) => { item.id !== updatedItem.id).concat[updatedItem]};

    Where item = {id: someID, value: someUpdatedValue}

    The main thing to notice is, that you need to pass an array to concat.
    So make sure that you put your value to be "pushed" inside a couple of square brackets, and you're good to go.
    This will give you the functionality you expected from push()

    You can use the + operator to "add" two arrays together, or by passing the arrays to join as parameters to concat().

    let arrayAB = arrayA + arrayB;
    let arrayCD = concat(arrayC, arrayD);
    

    Note that by using the concat method, you can take advantage of "chaining" commands before and after concat.

提交回复
热议问题