javascript - 更改函数中的第一个参数

标签 javascript function arguments apply

我想做这样的事情:

function start(){
    // Change the first argument in the argument list
    arguments[0] = '<h1>' + arguments[0] + '</h1>';

    // Call log with the new arguments
    // But outputs: TypeError: Illegal invocation
    log.apply(this, arguments);
}

function log(){ 
    console.log(arguments);   
    // should output -> ['<h1>hello<h1>', 'world', '!']
}


start('hello', 'world', '!');

最佳答案

您的代码确实有效(我刚刚在最新版本的 Firefox 中测试过)。

但是,我可以想象某些实现在将值作为值传递给 Function.prototype.apply 时,arguments 对象可能会出现问题>。所以尝试:

function start(){
    var args = Array.prototype.slice.call( arguments );
    args[0] = '<h1>' + args[0] + '</h1>';

    log.apply(this, args);
}

通过在 arguments 对象上调用 Array.prototype.slice,我们创建了一个“true”ECMAscript Array,我们可能需要它作为 .apply()

的第二个参数

关于javascript - 更改函数中的第一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14179076/

相关文章:

javascript - 尝试将旧的 React native 文件更新为 0.30

javascript - 传递带参数的函数,但不传递其执行结果

javascript - Javascript 中变量函数超出范围

java - 函数中的不同参数

python - 如何在 Python 2.7 中使用带参数的 super()?

Bash 函数参数未按预期传递

javascript - 使用 gtag.js 安装 Google 跟踪代码管理器

javascript - 为特定屏幕尺寸执行javascript

javascript - 使用 typescript 解析 SVG 转换属性

c - 为什么从结构传递指针需要额外的取消引用?