简体   繁体   English

为什么`Array.length`,`Function.length`,`String.length`等返回1?

[英]Why does `Array.length`, `Function.length`, `String.length`, etc return 1?

While teaching my JavaScript class yesterday, my students and I came across some interesting functionality that I thought might be worth capturing in a question and the answer I've come to. 在昨天教我的JavaScript课程时,我和我的学生遇到了一些有趣的功能,我认为这些功能值得在一个问题和我得到的答案中捕获。

Typing Array.length in the JS console in chrome returns 1 . 在chrome控制台Array.length chrome输入Array.length返回1

Likewise, Function.length returns 1 . 同样, Function.length返回1 This is important because: 这很重要,因为:

Every function in JavaScript is actually a Function object. JavaScript中的每个函数实际上都是一个Function对象。 (MDN JS Ref: Function) (MDN JS参考:功能)

Thus, Object.length and likely all other native objects will and should return 1 as the value of the length property. 因此, Object.length和可能所有其他本机对象将返回1作为length属性的值。

So, finally why is this behavior occurring? 那么,最后为什么会发生这种行为呢?

Function.length itself is the answer: Function.length本身就是答案:

Specifies the number of arguments expected by the function. 指定函数所需的参数数。 MDN JS Ref: Function.length MDN JS Ref:Function.length

When we write Function.length we are asking the Function constructor to tell us the number of formal, named parameters ("optional" - ie non-formal - parameters are accessed via the arguments property in the function body). 当我们编写Function.length我们要求Function构造Function告诉我们正式命名参数的数量(“可选” - 即非正式 - 参数通过函数体中的arguments属性访问)。 Because the Function constructor expects exactly 1 formal named parameter, the result is 1 : 因为Function构造Function正好需要1个正式命名参数,所以结果为1

new Function ([arg1[, arg2[, ... argN]],] functionBody)

functionBody is the single formal named parameter. functionBody是单个正式命名参数。 Therefore Function.length is 1 . 因此Function.length1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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