如何在 JavaScript 中將字符串轉換爲布爾值? - How can I convert a string to boolean in JavaScript?

問題:

Can I convert a string representing a boolean value (eg, 'true', 'false') into a intrinsic type in JavaScript?我可以將表示布爾值的字符串(例如,“true”、“false”)轉換爲 JavaScript 中的固有類型嗎?

I have a hidden form in HTML that is updated based upon a user's selection within a list.我在 HTML 中有一個隱藏表單,它根據用戶在列表中的選擇進行更新。 This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value.此表單包含一些表示布爾值的字段,並使用固有布爾值動態填充。 However, once this value is placed into the hidden input field it becomes a string.然而,一旦這個值被放入隱藏的輸入字段,它就會變成一個字符串。

The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.一旦將字段轉換爲字符串,我可以找到確定字段布爾值的唯一方法是依賴其字符串表示的文字值。

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

Is there a better way to accomplish this?有沒有更好的方法來實現這一點?


解決方案:

參考一: https://stackoom.com/question/16fV
參考二: How can I convert a string to boolean in JavaScript?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章