2012-03-20 89 views
5

我有以下代碼:如何在ActionScript中將字符串轉換爲布爾值?

var bool:String = "true"; 

沒有一個如果塊或switch語句,如何能這個被轉換成布爾對象?

+0

我不知道把我的頭頂部如何將其轉換成一個Boolean對象,但要注意,你不一定需要* *是一個布爾對象。這一切都取決於如何定義「假」如果你可以將它設置爲「false」的空字符串,那麼你可以簡單地說if(bool){whatever;}就像一個布爾對象。 – jhocking 2012-03-20 13:59:25

+0

謝謝,但我不能那樣做。 – Randyaa 2012-03-20 15:01:49

回答

17

您可以使用:

var boolString:String = "true"; 
var boolValue:Boolean = boolString == "true"; // true 
var boolString2:String = "false"; 
var boolValue2:Boolean = boolString2 == "true"; // false 

編輯

註釋以下建議使用

var boolValue:Boolean = (boolString == "true") ? true : false; 

這是沒有理由的代碼只是複雜的評估情況在部分:

(boolString == "true") 

使用三元運算符相當於:

var tempValue:Boolean = boolString == "true"; // returns true: this is what I suggested 
var boolValue:Boolean = tempValue ? true : false; // this is redundant 
+0

它不會工作....'boolValue'和'boolValue2'都是真的.. :) – Marcx 2012-03-20 14:06:15

+7

@Marcx表情符號不會讓你正確。 sch是對的,你不是。 – 2012-03-20 14:07:28

+0

我不認爲,他的回覆是不正確的... boolValue2應該是「假」,根據他的例子,但在現實中它是'真正的'... – Marcx 2012-03-20 14:10:32