【问题标题】:what this means in Javascript "typeof(arguments[0])"这在 Javascript "typeof(arguments[0])" 中意味着什么
【发布时间】:2014-11-12 09:42:31
【问题描述】:

我在我的代码中发现了这一点,可能有人在我之前做过。 我无法得到这行代码的确切作用。 arguments[0] 会在这里做什么。

        typeof(arguments[0])

整个代码是这样的:

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

问题是我总是把recommendedHeight 当作null。知道什么时候返回任何其他值吗?

【问题讨论】:

标签: javascript arguments typeof


【解决方案1】:

JavaScript 中的每个函数都会自动接收两个附加参数:thisargumentsthis 的值取决于调用模式,可以是全局浏览器上下文(例如,窗口对象)、函数本身或用户提供的值(如果您使用 .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;
}

希望有帮助!

【讨论】:

  • 很好的解释约书亚。
【解决方案2】:

这意味着:

如果arguments[0]的变量类型是数字,则recommendedHeight获取arguments[0]的值,否则设置为null。

可能参数是一个包含一些属性的数组,它的第一条记录应该包含推荐的高度。这就是为什么它应该是一个数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2016-06-28
    • 2012-05-23
    • 2019-08-07
    • 2010-10-21
    • 2016-05-18
    相关资源
    最近更新 更多