gpt4 book ai didi

javascript - 通过内部函数改变变量

转载 作者:行者123 更新时间:2023-11-28 13:08:42 24 4
gpt4 key购买 nike

可能有什么我不明白的地方。我有一个功能:

function doSmth(counter) {
counter++
console.log(counter);
doSmthElse(counter)
console.log(counter);
}

function doSmthElse(counter) {
counter = counter * 10
}
doSmth(30)

我以为第二个console.log中的结果应该是310,但实际上是31。为什么内部函数没有改变值?

最佳答案

在 JavaScript 中,作为参数传递给函数的数字作为值传递,而不是作为引用。

这意味着当您使用 doSmthElse(counter)counter 传递给 doSmthElse 函数时,您制作了一个副本counter 变量并将其传递给 doSmthElse

doSmthElse 实现中,当您执行 counter = counter * 10 时,您修改的是计数器的副本,而不是原始计数器。

解决问题的一个简单方法是返回更新后的值并将其分配回来:

function doSmth(counter) {
counter = doSmthElse(counter);
}

function doSmthElse(counter) {
return counter * 10;
}

请注意,如果您传递对象而不是数字,则不会出现此问题,因为对象是引用类型。传递给doSmthElse的是一个指向对象的指针:它代表实际的对象,不是它的副本:

function doSmth() {
doSmthElse(obj);
console.log(obj.counter); // counter has been multiplied by 10
}

function doSmthElse(obj) {
obj.counter = obj.counter * 10; // this works: we can modify the object
// that "obj" refers to.

obj = null // this has no effect outside of the current function: it
// simply modifies what the variable "obj" refers to in the
// current function.
}

关于javascript - 通过内部函数改变变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44603958/

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