原創–Javascript你意想不到的功能!!!

來源:互聯網
上載者:User

javascript不像python那樣可以方便地多行書寫字串,比如python可以這樣寫字串:

mStr="""   line1   line2   'line3'"""

而javascript只能用 + 與拼裝起來

mStr="line1"+      "line2"+      "'line3'";

由於習慣了python的這種用法,用起來javascript就特不爽。昨晚下班後回到房間打坐冥思,靈機一動,啊哈!原來javascript也可以方便地進行多行書寫。原理是構造一個函數,在函數內

寫注釋,如

fun=function(){    /*         line1         line2         line3   */}

然後把這個fun變成字串,只需簡單地和一個Null 字元串相加即可:

funStr=fun+"";

那麼就會得到像下面這樣的字串

"function(){    /*         line1         line2         line3   */}"

然後再寫一個函數去提取這個字串注釋裡的內容即可。而且不用處理 ' "的轉義。

完整代碼和樣本請看下面:

<html><head>    <meta http-equiv="content-type" content="text/html;charset=gbk">    <script>        function $string(fun){            var funStr=fun+"";            var reg=/\/\*/img;            var r=reg.exec(funStr);            var start=null;            var stop=null;            if(r){                start=reg.lastIndex;                reg=/\*\//img;                r=reg.exec(funStr);                if(r){                    stop=reg.lastIndex;                    return funStr.substring(start,stop-2);                }            }            throw "語法錯誤..."        }        var myString=$string(            function(){                 /*                    <table>                        <tr>                            <td>使用者名稱</td><td>密碼</td>                        </tr>                        <tr>                            <td style="widht:20px;">@name</td><td>zf123456</td>                        </tr>                    </table>                */            }        );        alert(myString);    </script></head><body></body></html>

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.