將“false”,”true”,”0″,”1″轉換為布爾

來源:互聯網
上載者:User

mass framework在最新版使用種子模組載入節點的屬性來判定是什麼環境:

<script type="text/javascript" debug="true" src="/scripts/mass.js"></script>

當頁面一載入此指令碼時,它通過 scripts = DOC.getElementsByTagName( "script" );node = scripts[ scripts.length - 1 ];得到此節點,然後我們使用getAttribute("debug")來得到這個值。

我計劃此屬性只能有四個合法的值,true, false, 0, 1,其他值或者不存在此屬性,則認為$["@debug"]為false。但不要忘記,通過getAttribute得到的值都是字串,然後Boolean("false")的結果為true,因此剩下的問題是如何轉換這四個值!

方法一,使用eval, Function進行解析

 var bool = node.getAttribute("debug")  $["@debug"] = /^(false|true|1|0)$/i.test(false) ? eval("0,"+bool) : false;

方法二,使用JSON.parse

//由一群的糖果男孩提供 var bool = node.getAttribute("debug")  $["@debug"] = /^(false|true|1|0)$/i.test(false) ? JSON.parse(bool) : false;

不過JSON有相容問題,而且這是種子模組,來不及調用其他模組……

方法三,使用正則

 var bool = node.getAttribute("debug") ; var match = bool.match(/^(true|1)$|^(false|0)$/) $["@debug"] = !!(bool && bool[1])

方法四,直接利用等號與短路

//由一群的abcd提供 沒有用到轉換,但很滿足我架構的需求 var str = node.getAttribute("debug") ; $["@debug"] = str =='true' || str=='1';

然後方法四完勝。這事情告訴我們,不要把情況想得太複雜……

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.