gpt4 book ai didi

Javascript:函数参数和参数[]

转载 作者:行者123 更新时间:2023-11-29 09:53:50 25 4
gpt4 key购买 nike

我是 Javascript 新手,所以请原谅基本问题。

我正在学习“面向 Web 开发人员的专业 Javascript”,在第 3 章“理解参数”部分,它讨论了使用 arguments[] 关键字访问函数参数。

其中一个示例表明您可以修改 arguments[] 中的值:

function twoNums(num1, num2) {
arguments[1] = 10;
console.log(arguments[0] + num2);
}

twoNums(4,8); output = 14

但它继续说“这种效果只有一种方式:更改命名参数不会导致参数中相应值的更改。”

但是,将代码更改为:

function twoNums(num1, num2) {
num2 = 10;
console.log(arguments[0] + arguments[1]);
}

twoNums(4,8); output = 14

产生相同的输出结果,因此“arguments[1]”中的值肯定会发生变化。

这是:

  • 书中有错误吗?
  • 我的理解有误吗?
  • 自本书撰写以来 Javascript 发生了什么变化?

谢谢,

尼尔

已回答:答案的组合解决了我的问题。谢谢大家。

最佳答案

它应该以这种方式工作,除非在严格模式下:

function foo(a) {
"use strict";
console.log(a, arguments[0]);
a = 10;
console.log(a, arguments[0]);
arguments[0] = 20;
console.log(a, arguments[0]);
}
foo(1);

// output:
// 1 1
// 10 1
// 10 20

ES5 规范在 section 10.6 上解决了这个问题:

NOTE 1 For non-strict mode functions the array index (defined in 15.4) named data properties of an arguments object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function’s execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. For strict mode functions, the values of the arguments object’s properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.

也许它在 ES3(以前的版本)上的工作方式不同,但我对此表示怀疑(因为他们必须为严格模式添加一个特殊情况)。

有趣的事实:函数中存在 eval 调用会影响参数对象在某些浏览器中的行为,这非常奇怪。使用非标准的 functionName.arguments 引用也会产生影响。参见 Why does an unexecuted eval have an effect on behavior in some browsers? ,以及我对此的回答。

关于Javascript:函数参数和参数[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16701353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com