2015-08-21 49 views
2

我有以下的html:如何避免在「匹配」沒有匹配時打破JavaScript?

<div id="box2"> 
    <p> this is some text and here is DAY 3 cool right </p> 
    <!-- In the previous line, change DAY to something else --> 
</div> 
<br> 
<select id="field"></select> 

下面的JavaScript正確填充選擇下拉,如果正則表達式「匹配」操作找到一個匹配。但是,如果將「day」的值更改爲「night」,則整個腳本將停止,但不會觸發警報框。有一些缺失的步驟?

var TextToSearch = document.getElementById('box2').innerHTML; 
var result = TextToSearch.match(/DAY.*?</gi); 
var select = document.getElementById("field"); 
if(result.length) 
{ 
    for(var i = 0; i < result.length; i++) 
    { 
     var option = document.createElement("option"); 
     option.value = i+1; 
     option.innerHTML = result[i]; 
     select.add(option); 
    } 
} 
alert("test"); 

這裏是一個小提琴:https://jsfiddle.net/uooeLk2c/1/

回答

4

Uncaught TypeError: Cannot read property 'length' of null

請務必檢查的result的價值,你嘗試獲得.length屬性之前。如果沒有匹配,則返回null

更改if(result.length)對於if(result !== null)

+0

1)看我的回答2)打開JavaScript控制檯:F12在大多數瀏覽器。 – Halcyon

6

如果沒有匹配,您可以使用||match()返回null當找不到匹配項時,那麼當您在null上使用length時,會引發錯誤。您可以使用||在不匹配時返回空數組。

var result = TextToSearch.match(/NIGHT.*?</gi) || []; 

通過使用此,您確保result將永遠的array不管的match()狀態。

Demo

var TextToSearch = document.getElementById('box2').innerHTML; 
 
var result = TextToSearch.match(/DAY.*?</gi) || []; 
 
var select = document.getElementById("field"); 
 

 
if (result.length) { 
 
    for (var i = 0; i < result.length; i++) { 
 
    var option = document.createElement("option"); 
 
    option.value = i + 1; 
 
    option.innerHTML = result[i]; 
 
    select.add(option); 
 
    } 
 
} 
 
alert("No Error");
<div id="box2"> 
 
    <p>this is some text and here is night 3 cool right</p> 
 
    <!-- In the previous line, change DAY to something else --> 
 
</div> 
 
<br> 
 
<select id="field"></select>

+1

刪除了我的重複答案+1 – anubhava

1

不需要檢查的長度。

只是檢查變量存在:

if (result) {

0

我想這樣的事情應該做的......

if (typeof result !== 'undefined' && result && result.length) 
{ 
/* your code here*/ 
}