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?
- 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
3 Answers
Reset to default 3Alternative:
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条)