这意味着什么在Javascript"typeof(arguments [0])"

pra*_*hmi 2 javascript arguments typeof

我在我的代码中找到了这个,可能有人在我之前做过.我无法得到这行代码究竟是做什么的.论证[0]会在这里做什么.

        typeof(arguments[0])
Run Code Online (Sandbox Code Playgroud)

整个代码是这样的:

 var recommendedHeight = (typeof(arguments[0]) === "number") ? arguments[0] : null;
Run Code Online (Sandbox Code Playgroud)

问题是我总是recommendedHeight这样null.任何想法何时返回任何其他值?

Jos*_*son 6

JavaScript中的每个函数都会自动接收两个附加参数:thisarguments.值this取决于调用模式,可以是全局浏览器上下文(例如,窗口对象),函数本身或用户提供的值(如果使用).apply().该arguments参数是传递给函数的所有参数的类数组对象.例如,如果我们定义了以下函数..

function add(numOne, numTwo) {
  console.log(arguments);
  return numOne + numTwo;
} 
Run Code Online (Sandbox Code Playgroud)

并且像这样使用它..

add(1, 4);

当然,这将返回5,并在控制台中显示arguments数组[1, 4].这允许你做的是传递和访问比你的函数定义的更多参数,强大的东西.例如..

add(1, 4, "extra parameter 1", "extra parameter 2", "extra parameter n");
Run Code Online (Sandbox Code Playgroud)

我们会在控制台中看到[1, 4, "extra parameter 1", "extra parameter 2", "extra parameter n"].现在我们的功能可以访问"extra parameter 1"via arguments[2].

您的代码检查参数数组中第一项的类型(例如,数字,字符串等),并使用三元运算符执行此操作.

扩展代码可能会更清晰:

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;
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!