簡體   English   中英

無法獲取未定義或空引用的屬性“長度”

[英]Unable to get property 'length' of undefined or null reference

我有以下代碼 - 它只是抓取文本框中的值,對字符串執行正則表達式,然后計算字符串值中的星號數:

var textBoxValue = $(textbox).val();

function countHowManyWildCards(stringToSearch) {

    var regex = new RegExp(/\*/g);
    var count = stringToSearch.toString().match(regex).length;
    return count;

}

if (countHowManyWildCards(textBoxValue) > 1) {

//Other code
}

代碼似乎有效,但出現錯誤:

stringToSearch.toString().match(regex).length;

錯誤說明:

無法獲取未定義或空引用的屬性“長度”

但我不清楚為什么代碼工作,但我仍然有這個錯誤? 有人可以告訴我為什么會這樣嗎?

由於match失敗並且沒有返回任何數組,因此調用.length會導致該錯誤。

要解決此問題,您可以使用:

var count = (stringToSearch.match(regex) || []).length;

match失敗時照顧這個案子。 || [] 匹配失敗時, || []將返回一個空數組, [].length將返回0

如果沒有匹配項, 則.match(regex)的返回值為null

如果stringToSearch不包含任何'*',則stringToSearch.toString()。match(regex)將返回null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM