gpt4 book ai didi

javascript - 如何在函数内部将未定义的 var 转换为对象

转载 作者:搜寻专家 更新时间:2023-11-01 05:29:39 24 4
gpt4 key购买 nike

有些事情我找不到答案或解释。让我们以下面的代码为例:

function fn(x){
x = {value: 10};
}
var a;
fn(a);

alert(a.value); //a is undefined

当我们通过该函数传递它时,a = {value: 10}; 不应该吗?

最佳答案

x 是本地范围的。您只传递 而不是引用。因此,您可能需要像这样返回并分配:

function fn(x){
x = {value: 10};
return x;
}
var a;
a = fn(a);

来自awesome article :

When passing in a primitive type variable like a string or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function.

function myfunction(x)
{
// x is equal to 4
x = 5;
// x is now equal to 5
}

var x = 4;
alert(x); // x is equal to 4
myfunction(x);
alert(x); // x is still equal to 4

Passing in an object, however, passes it in by reference. In this case, any property of that object is accessible within the function.

function myobject()
{
this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6

关于javascript - 如何在函数内部将未定义的 var 转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35099832/

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