2016-11-13 97 views
0

我有这个功能,我似乎无法工作。我希望它比较两个变量并设置第三个变量的值。如何比较两个变量并设置第三个变量的值

var win_lose; 
var this_roll = $('#past')[0].childNodes[9].textContent; 
var last_roll = $('#past')[0].childNodes[9].textContent; 

function compare() { 

    if (!(this_roll == last_roll)) { 
     win_lose = 'lose'; 
    } else { 
     win_lose = 'win'; 
    } 
    console.log(win_lose); 
} 

回答

3

你真的调用过这个函数吗?

var this_roll = $('#past')[0].childNodes[9].textContent; 
var last_roll = $('#past')[0].childNodes[9].textContent; 

function compare(this_roll, last_roll) { 
    var win_lose; //added new variable here 
    if (this_roll != last_roll) { 
     win_lose = 'lose'; 
    } else { 
     win_lose = 'win'; 
    } 
    return win_lose; 
} 

var res = compare(this_roll, last_roll); 
console.log(res); 

我还重写了你的if语句,不需要检查是否相等,然后反转。

我也将参数传递给一个函数,因为我有。

+0

* var *已经得到函数范围...它也是全局范围的一部分,所以范围不是他的问题... –

+0

但是,它是否设置了全局“win_lose”的值? – cbh1608

+0

@ cbh1608不,因此为什么我编辑包含回报。不要在函数内部设置全局变量,它可能会使其很难跟踪。取而代之的是让函数返回值,而这些值又可以被赋值。 –