gpt4 book ai didi

javascript:参数值更改会导致参数值更改吗?

转载 作者:行者123 更新时间:2023-11-30 12:11:06 26 4
gpt4 key购买 nike

在 w3cschool 中说“如果一个函数改变了参数的值,它不会改变参数的原始值。”

但是,我不太明白下面的例子:

function bar(a){
arguments[0] = 10;
console.log("a",a);//10
return a;
}
function foo(cc){
cc = 10;
return arguments[0];
}
console.log(bar(333));//10
console.log(foo(333));//10

我已经在 chrome 和 firefox 中测试过它们。根据我的理解,如果参数值的变化不能导致参数值的变化,为什么'bar'无法返回333?

最佳答案

给定一个函数:

function bar(a) {
arguments[0] = 10;
return a;
}

bar(50) 这样调用它会返回 10,因为 bar 范围内的值 被 10 替换了。 p>

“如果一个函数改变了参数的值,它不会改变参数的原始值。”的意思是:

var x = 90;
var y = bar(x);

console.log(y);
console.log(x);
// y is 10
// x is still 90

...不会更改 barx outside 的值。


有关详细信息,请参阅:

关于javascript:参数值更改会导致参数值更改吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33775559/

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