Array.push 返回推送值? [英] Array.push return pushed value?

查看:20
本文介绍了Array.push 返回推送值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改 Array.push() 以返回推送的对象而不是新数组的长度可能是一个坏主意,是否有任何实质性的原因?

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?

我不知道之前是否已经提出或询问过这个问题;Google 搜索仅返回与 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().

这是此功能的示例实现,请随时更正:

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({}));

例如,

其中 someFunction 修改作为第二个参数传入的对象.现在someArray的内容是[{"someKey": "hello world"}].

Where someFunction modifies the object passed in as the second parameter, for example. Now the contents of someArray are [{"someKey": "hello world"}].

这种方法有什么缺点吗?

Are there any drawbacks to this approach?

推荐答案

修改 Array.push() 以返回推送的对象而不是新数组的长度可能是一个坏主意,是否有任何实质性的原因?

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, i.e. to return the new length. 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.

然后你就可以做这样的事情:someFunction(value, someArray.push({}));

You would then be able to do something like this: someFunction(value, someArray.push({}));

呃,什么?是的,我的第二点已经开始了:-)

Uh, what? Yeah, my second point already strikes :-)

然而,即使您没有使用 push 这也无法理解您想要做什么.您应该表达的组合是将一个由键和值组成的对象添加到数组中".用更函数式的风格,让someFunction返回这个对象,你就可以写

However, even if you didn't use push this does not get across what you want to do. 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

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

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

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

这篇关于Array.push 返回推送值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆