简体   繁体   中英

what this means in Javascript “typeof(arguments[0])”

I have found this in my code, probably someone has done prior to me. I am unable to get what exactly this line of code does. what will arguments[0] do here.

        typeof(arguments[0])

Entire code is this:

 var recommendedHeight = (typeof(arguments[0]) === "number") ? arguments[0] : null;

The problem is I always get recommendedHeight as null . any idea when this returns any other value ?

Every function in JavaScript automatically receives two additional parameters: this and arguments . The value of this depends on the invocation pattern, could be the global browser context (eg, window object), function itself, or a user supplied value if you use .apply() . The arguments parameter is an array-like object of all parameters passed into the function. For example if we defined the following function..

function add(numOne, numTwo) {
  console.log(arguments);
  return numOne + numTwo;
} 

And used it like so..

add(1, 4);

This would return 5 of course, and also show the arguments array in the console [1, 4] . What this allows you to do is pass and access more parameters than those defined by your function, powerful stuff. For instance..

add(1, 4, "extra parameter 1", "extra parameter 2", "extra parameter n");

We would see in the console [1, 4, "extra parameter 1", "extra parameter 2", "extra parameter n"] . Now in our function we could access "extra parameter 1" via arguments[2] .

Your code checks the type of the first item in the arguments array (eg, number, string, etc) and it does so using a ternary operator.

Expanding your code may make it more clear:

var recommendedHeight;

//if the first argument is a number
if ( typeof(arguments[0]) === "number" ) {
  //set the recommendedHeight to the first argument passed into the function
  recomendedHeight = arguments[0];
} else {
  //set the recommended height to null
  recomendedHeight = null;
}

Hope that helps!

That means:

If the variable type of arguments[0] is a number, then recommendedHeight gets the value of arguments[0], otherwise set it to null.

Probably arguments is an array containing some attributes, and its first record should contain the recommended height. This is why it should be a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM