JavaScript 中的每个函数都会自动接收两个附加参数:this 和 arguments。 this 的值取决于调用模式,可以是全局浏览器上下文(例如,窗口对象)、函数本身或用户提供的值(如果您使用 .apply())。 arguments 参数是传递给函数的所有参数的类数组对象。例如,如果我们定义了以下函数..
function add(numOne, numTwo) {
console.log(arguments);
return numOne + numTwo;
}
然后像这样使用它..
add(1, 4);
这当然会返回 5,并且还会在控制台 [1, 4] 中显示参数数组。这允许你做的是传递和访问比你的函数定义的参数更多的参数,强大的东西。比如……
add(1, 4, "extra parameter 1", "extra parameter 2", "extra parameter n");
我们会在控制台中看到[1, 4, "extra parameter 1", "extra parameter 2", "extra parameter n"]。现在在我们的函数中,我们可以通过arguments[2] 访问"extra parameter 1"。
您的代码检查参数数组中第一项的类型(例如,数字、字符串等),并使用三元运算符进行检查。
扩展你的代码可能会更清楚:
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;
}
希望有帮助!