如何在javascript中为具有相同名称的变量赋值参数?

时间:2021-05-07 16:47:55

Why the following code doesn't alert undefined?

为什么以下代码不会提示未定义?

function test(param){ 
     var param =  param;
     alert(param);
 } 
test("SO"); // alerts SO

How is that the param that is being assigned to the local variable is matched with the argument of the function, and not with the local variable itself?
Does right values have a "matching preference" for the the function arguments or what is the cause?

如何将赋给局部变量的参数与函数的参数匹配,而不是与局部变量本身匹配?右值是否具有函数参数的“匹配首选项”或原因是什么?

1 个解决方案

#1


2  

There are two parts in

有两个部分

var param =  param;

The first one is the var declaration :

第一个是var声明:

var param;

The second one is the assignement :

第二个是分配:

param = param;

The var declaration does nothing, as the variable already exists (the scope of a variable is the whole function call). And the assignement does nothing, as it keeps the same value.

var声明什么都不做,因为变量已经存在(变量的范围是整个函数调用)。并且该任命没有任何作用,因为它保持相同的价值。

You could check that by assigning a different value :

您可以通过分配不同的值来检查:

function test(param){ 
     console.log('1', param) // logs "SO"
     var param =  param+"4";
     console.log('2', param) // logs "SO4"
} 
test("SO");

#1


2  

There are two parts in

有两个部分

var param =  param;

The first one is the var declaration :

第一个是var声明:

var param;

The second one is the assignement :

第二个是分配:

param = param;

The var declaration does nothing, as the variable already exists (the scope of a variable is the whole function call). And the assignement does nothing, as it keeps the same value.

var声明什么都不做,因为变量已经存在(变量的范围是整个函数调用)。并且该任命没有任何作用,因为它保持相同的价值。

You could check that by assigning a different value :

您可以通过分配不同的值来检查:

function test(param){ 
     console.log('1', param) // logs "SO"
     var param =  param+"4";
     console.log('2', param) // logs "SO4"
} 
test("SO");