作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑:
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>");
简单
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>");
到这里为止还好
从这里我发现自己真的很困惑,
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?
有什么建议吗?可以说吗
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/
我是一名优秀的程序员,十分优秀!