Does Array.push return a pushed value?

Are there any significant reasons why changing Array.push()to return an object, rather than the length of a new array, might be a bad idea?

I do not know if this has already been proposed or asked; Google searches returned only a huge number of questions related to current features Array.push().

Here is an example implementation of this feature, feel free to fix it:

;(function() {
    var _push = Array.prototype.push;
    Array.prototype.push = function() {
        return this[_push.apply(this, arguments) - 1];
    }
}());

Then you can do something like this:

var someArray = [],
    value = "hello world";

function someFunction(value, obj) {
    obj["someKey"] = value;
}

someFunction(value, someArray.push({}));

Where someFunctionchanges the object passed as the second parameter, for example. Now the contents are someArrayequal [{"someKey": "hello world"}].

Are there any flaws in this approach?

+4
source share
5 answers

Are there any significant reasons why changing Array.push()to return an object, rather than the length of a new array, might be a bad idea?

, : , Array::push , , .. . , , .

, .

- : someFunction(value, someArray.push({}));

, ? , : -)

, push, , . , , - " , ". , someFunction ,

var someArray = [],
    value = "hello world";

function someFunction(value, obj) {
    obj["someKey"] = value;
    return obj;
}

someArray.push(someFunction(value, {}));
+5
+4
var arr = [];
var element = Math.random();
assert(element === arr[arr.push(element)-1]);
+2

ES6 , push:

class XArray extends Array {
   
   push() {
     super.push(...arguments);
     return (arguments.length === 1) ? arguments[0] : arguments;
   }
 
}
//---- Application
let list  = [1, 3, 7,5];

list = new XArray(...list);

console.log(
  'Push one item : ',list.push(4)
);

console.log(
  'Push multi-items :', list.push(-9, 2)
);

console.log(
   'Check length :' , list.length
)
Hide result
+2

.

TL;DR;
, array.concat[].

concat - "" "" . , , .

newArray = oldArray.concat[newItem];

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

item = {id: someID, value: someUpdatedValue}

, concat.
, "" , .
, push()

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

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

Source: https://habr.com/ru/post/1538512/


All Articles