在 Javascript 中更改传递变量的值而不返回? [英] Change value of passed variable in Javascript without return?
问题描述
我有函数 change(x) 它接受一个整数并改变它的值
I have the function change(x) which takes an integer and changes its value
function change(x) {
x=26;
}
然后我创建一个变量并尝试更改它的值
Then I make a variable and I try to change its value
window.onload=function(){
var a = 10;
change(a);
console.log(a);
}
a 没有像我期望的那样改变.是否可以在不使用 return 的情况下以简单的方式在 JavaScript 中实现这种行为?我宁愿避免使用对象和全局变量.
a doesn't change as I would expect. Is it possible to achieve this behaviour in JavaScript in a simple way without using return? I would prefer to avoid objects and globals.
这是我的全部代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function change(x) {
x=26;
}
window.onload=function(){
var a = 10;
change(a);
console.log(a);
}
</script>
</body>
</html>
推荐答案
JavaScript 总是按值传递参数,所以你不能像你原来写的那样做.
JavaScript always passes arguments by value, so you can't do it as you originally written.
然而,一个对象的值是一个引用,所以你可以使用一个对象.
However, an object's value is a reference, so you could use an object.
但是,对于这个用例来说,这会令人困惑.您应该让该函数返回转换后的数字.
However, that would be confusing for this use case. You should have that function return the transformed number.
这篇关于在 Javascript 中更改传递变量的值而不返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!