Don't understand this JS [closed]
function decimalToHex(d, padding) {
var hex = Number(d).toString(16);
/*I dont understand this part: does this mean if padding gets a value = "undefined". It'd be equal to "justchecking" in this case.
What is a value of "undefined" then? is it really necessary this if-statement? */
padding = typeof (padding) === "undefined" || padding === null ? padding = "justchecking" : padding;
whil开发者_开发技巧e (hex.length < padding) {
hex = "0" + hex;
}
return hex;
}
Thanks for your explanation...
padding = typeof (padding) === "undefined" || padding === null ? padding = "justchecking" : padding;
There is an error in the conditional above it should read:
padding = typeof (padding) === "undefined" || padding === null ? "justchecking" : padding;
But in any case this is equivalent to writing:
if(typeof(padding) == "undefined" || padding === null)
{
padding = 'justchecking';
}
What it is doing is seeing if padding exists and is defined in a most explicit way because just checking if(padding)
will return falsy if padding is "" or 0. But if you check for the type of a variable and it hasn't been defined then it gets the special string "undefined". If you just check for null it could be defined because null is different from the truthiness of typeof undefined. A little overview is here: http://scottdowne.wordpress.com/2010/11/28/javascript-typeof-undefined-vs-undefined/ and you can also find a discussion of it in Douglas Crockfords The definitive guide I think.
It's a ternary operator. Simply put, it's a condensed version of an if/else block, in the format:
condition ? true expression : false expression;
In your case it defaults padding
to justchecking
.
This just assigns the default value "justchecking" for the padding variable if no padding is present.
It could be also written as:
padding = padding || "justchecking";
... although it's not entirely equivalent as this would also replace the value of 0 with the default.
It means: assign "justchecking" to the variable "padding" if it is defined and is null.
精彩评论