2015-08-21 46 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*/ 
}