将自变量前置到自变量,然后应用

Prepend argument to arguments then apply

本文关键字:自变量 然后 应用      更新时间:2023-09-26

我有一个函数message,它使用一个参数来定义消息的类型,然后它将任何其他参数连接起来形成消息,纯粹是一个细节。

它看起来像这样:

function message(type) {
    var msg = _.rest(arguments).join(" ");
    // Really the type will be used to set the class on a div
    // But I'm just using console.log to keep it simple for now.
    console.log(type + ": " + msg);
}

我想提供助手函数errorwarninginfo,它们只是用正确的类型调用message。我只是不确定该怎么做。我想不出两种方法,但我不确定我做得是否正确,或者我可能把事情搞得过于复杂了。

第一种方法似乎有点多余,制作一个包含第一个arg和自变量的新数组,然后将其压平

message.apply(this, _.flatten(["error", arguments]));

第二种方式感觉有点。。。凌乱的

Array.prototype.unshift.call(arguments, "error");
message.apply(this, arguments);

尽管根据我的经验:

(function() {
    Array.prototype.unshift.call(arguments, 0);
    console,log(arguments);
})(1, 2, 3);

我得到以下输出:

[0, 1, 2, 3, undefined, undefined, undefined, ..., undefined]
var args = Array.prototype.slice.call(arguments); // Make real array from arguments
args.unshift("error");
message.apply(this, args);

请参阅如何将";论点";对象到JavaScript中的数组?

在ES5中,这可能比先转换为实数数组,然后转换为unshift:效率略高

var args = Array.prototype.concat.apply(["error"], arguments);
message.apply(this, args);

编辑:更好地避免扁平化输入阵列:

var args = ["error"];
args.push.apply(args, arguments);
message.apply(this, args);