如何在“匹配”时避免打破JavaScript没有匹配? [英] How to avoid breaking javascript when "match" has no matches?

查看:86
本文介绍了如何在“匹配”时避免打破JavaScript没有匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html:

 < div id =box2> 
< p>这是一些文字,这里是第3天很酷的< / p>
<! - 在前一行中,将DAY更改为其他内容 - >
< / 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.value = i + 1;
option.innerHTML = result [i];
select.add(option);
}
}
alert(test);

这是一个小提琴: https://jsfiddle.net/uooeLk2c/1/

解决方案

$

















$

在尝试获取 .length 属性之前,请确保检查 result 的值。



.match 如果没有匹配,则返回 null 对于 if(result!== null)更改 if(result.length) code>。


I have the following html:

<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>

The following javascript correct populates the select drop down, if the regex "match" operation finds a match. However, If I change the value of "day" to "night" the entire script stops, It does not not trigger the alert box. Is there some missing step?

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");

Here is a fiddle: https://jsfiddle.net/uooeLk2c/1/

解决方案

Uncaught TypeError: Cannot read property 'length' of null

Make sure you check the value of result before you try to get the .length property.

.match returns null if there is no match.

Change if(result.length) for if(result !== null).

这篇关于如何在“匹配”时避免打破JavaScript没有匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆