javascript - if Not undefined and indexOf ('foo') do something - Stack Overflow

So I'm trying to call where if not undefined and index is foo so I use:if (typeof(getdata(js, 

So I'm trying to call where if not undefined and index is foo so I use:

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

This works fine but I dont want to call the getdata twice. Is there way to say if getdata is not undefined and the indexOf is foo then do something, without calling the getdata() function twice?

So I'm trying to call where if not undefined and index is foo so I use:

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

This works fine but I dont want to call the getdata twice. Is there way to say if getdata is not undefined and the indexOf is foo then do something, without calling the getdata() function twice?

Share Improve this question asked Apr 17, 2012 at 1:14 jQuerybeastjQuerybeast 14.5k39 gold badges120 silver badges198 bronze badges 3
  • Why are you checking if the return value of a function is undefined? – Sam Dufel Commented Apr 17, 2012 at 1:19
  • The function gets values from localstorage, so sometimes if the users clears its cache, it return undefined. If you dont call that, you get an error – jQuerybeast Commented Apr 17, 2012 at 1:27
  • IMO, you'd be better off catching that in the function and returning null instead. – Sam Dufel Commented Apr 17, 2012 at 18:29
Add a ment  | 

3 Answers 3

Reset to default 3

Alternative:

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

While this allows you to get away with a single check, involving a regular expression for such a simple test could be frowned upon :)

You're better off using a local variable for storing the oute of the function call:

var data = getdata(js, "box1");

if (data && data.indexOf("foo") ==! -1) {
    // do something
}

Also note that typeof is an operator and not a function:

typeof something // instead of typeof(something)

Have you tried

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

}

You can read the indexOf of the value or an empty string if the value is undefined or null.

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

Hopefully your function will only return a string, undefined or null.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744383302a4571537.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信