javascript - Can't store a boolean returned by a function in a variable -
this question has answer here:
i don't know if bug, feels kind of strange. can store boolean returned function in variable using javascript? whenever try store boolean value in variable returned function, gets changed string.
i have following function converts string boolean
function str2bool(strvalue){ console.log("value - " + strvalue); console.log("type - " + typeof strvalue); return (strvalue && typeof strvalue == 'string') ? (strvalue.tolowercase() == 'true') : (strvalue == true); }
i've found function somewhere here on stackoverflow, not remember it's author, if reading this, sorry me not giving proper credits:)
i have javascript line, looks follows:
target.prop('disabled',str2bool(booleaninstringformat)); console.log("typeof str2bool return - " + typeof str2bool(booleaninstringformat));
if use way, everyting works fine, str2bool function returns following lines console:
value - false
type - string
and line after main function returns:
typeof of str2bool function - boolean
but if try store return value of str2bool in variable, , use afterwards, prop function won't work, because apparently variable use store return value of str2bool becomes string. if run code following results:
status = str2bool(booleaninstringformat); console.log("typeof status - " + typeof status); target.prop('disabled',status);
the results following:
value - false
type - string
typeof status - string
end result target remains disabled
so, why typeof variable in store return of function changed string?
because use global variable status
, appeared property of global object window
, property string.
the window.status.
you change other variable name, better, avoid using global variable.
(function(){ var status = str2bool('false'); console.log(typeof status); }());
Comments
Post a Comment