如果不是未定义和索引('foo')做某事

if Not undefined and indexOf ('foo') do something

本文关键字:foo 索引 如果不 未定义      更新时间:2023-09-26

所以我试图调用where,如果不是未定义并且索引是foo,所以我使用:

if (typeof(getdata(js, 'box1')) != "undefined" 
&& (getdata(js, 'box1')).indexOf('foo') >= 0) {
      // Do something
   }

这工作正常,但我不想调用两次 getdata。有没有办法说如果getdata不是未定义的,并且 indexOf 是 foo,那么做一些事情,而不调用 getdata() 函数两次?

备选方案:

if (/foo/.test(getdata(js, "box1"))) {
    // do something
}

虽然这允许您通过一次检查来侥幸逃脱,但涉及如此简单的测试的正则表达式可能会令人皱眉:)

最好使用局部变量来存储函数调用的结果:

var data = getdata(js, "box1");
if (data && data.indexOf("foo") ==! -1) {
    // do something
}

另请注意,typeof 是运算符而不是函数:

typeof something // instead of typeof(something)

你试过吗

var data = getdata(js, 'box1');
if(typeof(data) != 'undefined' && data.indexOf('foo') >= 0) {
}

如果值未定义或为 null,则可以读取值的 indexOf 或空字符串。

if ( (getdata(js, 'box1') || '').indexOf('foo') !=-1) {
      // Do something
   }

希望您的函数只会返回一个字符串,未定义或 null。