简体   繁体   English

Array.push 返回推送值?

[英]Array.push return pushed value?

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?为什么修改Array.push()以返回推送的对象而不是新数组的长度可能是一个坏主意,是否有任何实质性的原因?

I don't know if this has already been proposed or asked before;我不知道这是否已经被提议或询问过; Google searches returned only a myriad number of questions related to the current functionality of Array.push() .谷歌搜索只返回了无数与Array.push()的当前功能相关的问题。

Here's an example implementation of this functionality, feel free to correct it:这是此功能的示例实现,请随时更正:

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

You would then be able to do something like this:然后,您将能够执行以下操作:

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

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

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

Where someFunction modifies the object passed in as the second parameter, for example.例如,其中someFunction修改作为第二个参数传入的对象。 Now the contents of someArray are [{"someKey": "hello world"}] .现在someArray的内容是[{"someKey": "hello world"}]

Are there any drawbacks to this approach?这种方法有什么缺点吗?

See my detailed answer here在这里查看我的详细答案

TLDR; TLDR;
You can get the return value of the mutated array, when you instead add an element using array.concat[] .当您改为使用array.concat[]添加元素时,您可以获得变异数组的返回值。

concat is a way of "adding" or "joining" two arrays together. concat是一种将两个数组“添加”或“连接”在一起的方法。 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}其中item = {id: someID, value: someUpdatedValue}

The main thing to notice is, that you need to pass an array to concat .需要注意的主要事情是,您需要将数组传递给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()这将为您提供push()所期望的功能

You can use the + operator to "add" two arrays together, or by passing the arrays to join as parameters to concat() .您可以使用+运算符将两个数组“添加”在一起,或者将要连接的数组作为参数传递给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 .请注意,通过使用concat方法,您可以利用concat之前和之后的“链接”命令。

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?为什么修改Array.push()以返回推送的对象而不是新数组的长度可能是一个坏主意,是否有任何实质性的原因?

Of course there is one: Other code will expect Array::push to behave as defined in the specification, ie to return the new length.当然有一个:其他代码将期望Array::push的行为符合规范中的定义,即返回新的长度。 And other developers will find your code incomprehensible if you did redefine builtin functions to behave unexpectedly.如果您确实重新定义了内置函数以使其行为异常,其他开发人员会发现您的代码难以理解。

At least choose a different name for the method.至少为该方法选择一个不同的名称。

You would then be able to do something like this: someFunction(value, someArray.push({}));然后,您将能够执行以下操作: someFunction(value, someArray.push({}));

Uh, what?呃,什么? Yeah, my second point already strikes :-)是的,我的第二点已经发生了:-)

However, even if you didn't use push this does not get across what you want to do.但是,即使您没有使用push这也不会达到您想要做的事情。 The composition that you should express is "add an object which consist of a key and a value to an array".您应该表达的组合是“将由键和值组成的对象添加到数组中”。 With a more functional style, let someFunction return this object, and you can write用更函数式的风格,让someFunction返回这个对象,就可以写了

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

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

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

Just as a historical note -- There was an older version of JavaScript -- JavaScript version 1.2 -- that handled a number of array functions quite differently.正如一个历史记录——有一个旧版本的 JavaScript—— JavaScript version 1.2 ——它处理许多数组函数的方式完全不同。

In particular to this question, Array.push did return the item, not the length of the array.特别是对于这个问题, Array.push确实返回了项目,而不是数组的长度。

That said, 1.2 has been not been used for decades now -- but some very old references might still refer to this behavior.也就是说, 1.2已经几十年没有使用了——但一些非常古老的参考资料可能仍然提到这种行为。

http://web.archive.org/web/20010408055419/developer.netscape.com/docs/manuals/communicator/jsguide/js1_2.htm http://web.archive.org/web/20010408055419/developer.netscape.com/docs/manuals/communicator/jsguide/js1_2.htm

By the coming of ES6 , it is recommended to extend array class in the proper way , then , override push method :随着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 )

var arr = [];
var element = Math.random();
assert(element === arr[arr.push(element)-1]);

Method push() returns the last element added, which makes it very inconvenient when creating short functions/reducers.方法push()返回最后添加的元素,这使得在创建短函数/reducer 时非常不方便。 Also, push() - is a rather archaic stuff in JS.此外, push() - 在 JS 中是一个相当古老的东西。 On ahother hand we have spread operator [...] which is faster and does what you needs: it exactly returns an array.另一方面,我们有传播运算符[...]它更快并且可以满足您的需求:它完全返回一个数组。

// to concat arrays
const a = [1,2,3];
const b = [...a, 4, 5];
console.log(b) // [1, 2, 3, 4, 5];

// to concat and get a length
const arrA = [1,2,3,4,5];
const arrB = [6,7,8];
console.log([0, ...arrA, ...arrB, 9].length); // 10

// to reduce
const arr = ["red", "green", "blue"];
const liArr = arr.reduce( (acc,cur) => [...acc, `<li style='color:${cur}'>${cur}</li>`],[]);
console.log(liArr);
  //[ "<li style='color:red'>red</li>", 
  //"<li style='color:green'>green</li>", 
  //"<li style='color:blue'>blue</li>" ]

How about doing someArray[someArray.length]={} instead of someArray.push({})?用 someArray[someArray.length]={}代替 someArray.push({}) 怎么样? The value of an assignment is the value being assigned.赋值的值是被赋值的值。

 var someArray = [], value = "hello world"; function someFunction(value, obj) { obj["someKey"] = value; } someFunction(value, someArray[someArray.length]={}); console.log(someArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM