2011-12-15 60 views
0

我想反轉布爾值(toggle);Javascript:反轉布爾值不起作用

var current_state=$.cookie('state'); 
if(current_state==null) { 
    current_state=false; 
} 
console.log(current_state); 
current_state=(!current_state); 
console.log(current_state); 

$.cookie('state', current_state, { expires: 7, path: '/' }); 

在我看來,第二console.log應顯示第一個相反的,但兩個電話報告false。這是什麼?

+1

你爲什麼要重新聲明「current_state」? –

+0

如果你試過這個,該怎麼辦? 'var_current_state = $ .cookie('state')==「false」?false:true;' – Cipi

+0

如果你不需要做'($ .cookie('state')==「false」)?false:true ;'因爲條件評估爲真或假,所以只要做到這一點:'var current_state =($ .cookie('state')!=「false」);' –

回答

4

您的$.cookie('state')似乎是一個字符串(「false」)。

作爲證明,參見(也在this jsfiddle)以下代碼:

var current_state='false'; 
if(current_state==null) { 
    current_state=false; 
} 
console.log(current_state); 
var current_state=(!current_state); 
console.log(current_state); 

它輸出false兩次。

爲什麼?因爲你檢查它是否爲空並且不支持其他情況。

你可以做這樣的事情:

var current_state='false'; 
if(current_state==null || 
    current_state==false || 
    current_state=='false') { 
    current_state = false; 
}else{ 
    current_state = true; 
} 
console.log(current_state); 
current_state=(!current_state); 
console.log(current_state); 

和您的代碼將輸出布爾truefalse,然後再反布爾值。

+0

謝謝,將第一行更改爲'var current_state = $。cookie('webcam_auto_cycle')=='1';'並且現在按預期工作。似乎如果我通過JQuery cookie插件編寫一個布爾值,它將被轉換爲一個字符串。 – gorootde

+0

@k_wave:取決於插件。歡迎您:) – Tadeck

+0

@rohk:你完全錯誤 - 它取決於字符串。例如'!!'false''會給你'true'(見[this jsfiddle](http://jsfiddle.net/msBHk/))。使用'!!'進行轉換對整數(不是字符串!)起作用。 – Tadeck

3

您確定在current_state不是null的情況下它確實是一個布爾值嗎?也許這是一個字符串?

+0

+1這是其他問題的答案。當然,我的回答是另一個:) – Tadeck

0

的問題是,current_state不是一個布爾值,但字符串

var current_state=$.cookie('state'); 
if(current_state==null) { 
    current_state=false; 
} 

console.log(current_state); 
var current_state= current_state == 'false' ? "true" : "false"; // (!current_state); 
console.log(current_state); 
$.cookie('state', current_state);