为什么JavaScript会记录它" 0"?

时间:2017-05-29 18:01:46

标签: javascript

此代码将输出记录为零。输出应为6。



function sum(a,b){
  r=a+b;
  return r; 
}

r=sum(2,9);
r1=sum(1,4);
diff=r-r1;

console.log(diff);




4 个答案:

答案 0 :(得分:6)

当您在功能中声明var变量localy时,您将使用r关键字,否则您将遇到范围冲突r函数内部将被声明为globular,并被视为与函数外的r变量相同的变量:

function sum(a,b){
    var r=a+b;
    return r; 
}

希望这有帮助。

function sum(a,b){
    var r=a+b;
    return r; 
}

r=sum(2,9);
r1=sum(1,4);
diff=r-r1;

console.log(diff);

答案 1 :(得分:4)

在声明变量时需要使用var。如果不使用function sum(a,b){ r=a+b; // This ends up being a reference to the same `r` as below return r; } r=sum(2,9); // This creates a global variable called r and sets it to 11 r1=sum(1,4); // This sets global `r` to 5 (because of the r=a+b in sum() diff=r-r1; // 5 - 5 is 0 console.log(diff); ,则隐式创建全局变量。

function sum(a,b){
    var r=a+b; // Now this r is local to the sum() function
    return r; 
}

var r=sum(2,9); // Now this r is local to whatever scope you are in
var r1=sum(1,4);
var diff=r-r1;
console.log(diff);

而是这样做:

CREATE TEMP VIEW 
dist_matrix(idA, idB, dist) AS 
    SELECT A.id, B.id, dist_score(A.lat, A.lon, B.lat,B.lon) AS dist
    FROM bar_pos AS A, bar_pos AS B 
    WHERE A.id > B.id
    ORDER BY dist;

答案 2 :(得分:2)

forr的内部和外部都被引用。它不是局部变量,而是存在于函数之外。对sum的任何调用都将覆盖之前sum的值。

r特别会将r1=sum(1,4);r设置为r1,因此5将为diff

答案 3 :(得分:0)

这是因为你没有在

中声明变量r

使用var keyword函数。因此,它在全局范围内。

当您执行此操作时r1 = sum(1,4),r的值将被覆盖为

5且r1的值也是5.因此r-r1的差值变为

out为0。

为避免这种情况,您可以使用var关键字在函数内声明r。

function sum(a,b){
    var r=a+b;
    return r; 
}

r=sum(2,9);
r1=sum(1,4);
diff=r-r1;

console.log(diff);

这会有所帮助。