与过滤器一起使用undefined

时间:2019-04-25 14:55:15

标签: javascript

使用undefined检查是否合适?

var someArray = [{pattern:/runtime/, aProperty:"tag"},
                 {pattern:/football/, aProperty:"blargh"},
                 {pattern:/restaurant/, aProperty:"olives"}]

var runtimeString = "This is a runtime string provided by a user";

/** The string provided by a user might not actually have a match in
someArray, in which case validItem would be undefined. Is there any danger 
or readability problem with comparing validItem to undefined to determine 
whether "filter" returned a result? **/

var validItem = someArray.filter(obj => obj.pattern.test(runtimeString))[0];
if (validItem !== undefined) {
    console.log("The matching item aProperty is: " + validItem.aProperty);
} else {
    console.log("There was no matching item");
}

0 个答案:

没有答案