gpt4 book ai didi

javascript - 参数传递: In and Out

转载 作者:行者123 更新时间:2023-12-02 15:41:21 25 4
gpt4 key购买 nike

考虑:

Primitive data types are passed by value in JavaScript. This means that a copy is effectively made of a variable when it is passed to a function, so any manipulation local to the function leaves the original variables untouched.

function fiddle(arg1) {
arg1 = "Fiddled with";
console.log("In function fiddle str = "+arg1+"<br>");
}
var str = "Original Value";
console.log("Before function call str = "+str+"<br>");
fiddle(str);
console.log("After function call str ="+str+"<br>");

enter image description here

简单

composite types such as arrays and objects if used, they are passed by reference rather than value

考虑以下修改之前的 fiddle() 函数:

function fiddle(arg1) {
arg1[0] = "Fiddled with";
console.log("In function fiddle arg1 = "+arg1+"<br>");
}
var arr = ["Original", " Original ", " Original "];
console.log("Before function call arr = "+arr+"<br>");
fiddle(arr);
console.log("After function call arr ="+arr+"<br>");

enter image description here

到这里为止还好

从这里我发现自己真的很困惑,

function fiddle(arg1) {
arg1 = ["Blasted!","Blasted!"];
console.log("In function fiddle arg1 = "+arg1+"<br>");
}
var arr = ["Original", " Original ", " Original "];
console.log("Before function call arr = "+arr+"<br>");
fiddle(arr);
console.log("After function call arr ="+arr+"<br>"); // Why this hasn't changed?

enter image description here

有什么建议吗?可以说吗

composite types such as arrays and objects if used, they are passed by reference rather than value

在这种情况下也是如此吗?

最佳答案

看起来很清楚,在 fiddle 中,您正在用您当场创建的数组覆盖对 arr 的引用。您从未通过其引用触及 arr 本身,而只是引用,因此一旦您再次外出,arr 仍然是原始数组。

关于javascript - 参数传递: In and Out,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32543039/

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