正則匹配的test函數

來源:互聯網
上載者:User

var fnTest = /xyz/.test(function(){xyz;}) ? /b_superb/ : /.*/;對於其中Regex匹配函數test的用法,我很是迷惑:
/xyz/.test(function(){xyz;})我查閱了Mozilla developer center中關於test函數的描述:
Executes the search for a match between a regular expression and a specified string. Returns true or false.
字串中是否有匹配Regex的子字串。返回true或false。
其文法格式:
regexp.test([str])注意這裡的參數是字串,根本沒有提到test函數的參數可以是函數的說法。
我試著修改這段奇怪的代碼,得到了一些運行結果: 複製代碼 代碼如下:/xyz/.test("xyz"); // true
/xyz/.test(function(){"xyz";}); // false
/xyz/.test(function(){return "xyz";}); // true
/xyz/.test(function(){return xyz;}); // true
/xyz/.test(function(){return axyz;}); // true
/xyz/.test(function(){return "axyz";}); // true
/xyz/.test(function(){return "xayz";}); // false怎麼回事?

華麗的分割線
=======================================
我終於知道了,卻原來在test內部進行了類型轉換,下面代碼: 複製代碼 代碼如下:/xyz/.test(function(){xyz;});

等價於: 複製代碼 代碼如下:/xyz/.test((function(){xyz;}).toString());

又等價於: 複製代碼 代碼如下:/xyz/.test("function(){xyz;}");

那麼為什麼下面的代碼返回false呢? 複製代碼 代碼如下:/xyz/.test(function(){"xyz";});

我們執行下這行代碼就知道了: 複製代碼 代碼如下:// 這行代碼的執行結果是:"function(){}"
(function(){"xyz";}).toString();

所以我們可以寫出更加詭異的代碼來迷惑大家了 複製代碼 代碼如下:/function/.test(function(){}); // true
// b 表示文字邊界(對英文而言的)
/b_superb/.test(function(){this._super();}); // true

聯繫我們

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