表达式 123['toString'].length + 123 的输出
理解 JavaScript 函数的 length 属性计算规则
问题
123['toString'].length + 123 的输出值是多少?
解答
要理解这个表达式,需要先了解函数的 length 属性。
函数的 length 属性
函数的 length 属性表示第一个具有默认值之前的参数个数。
function fn1(name) {}
function fn2(name = '林三心') {}
function fn3(name, age = 22) {}
function fn4(name, age = 22, gender) {}
function fn5(name = '林三心', age, gender) {}
console.log(fn1.length) // 1
console.log(fn2.length) // 0
console.log(fn3.length) // 1
console.log(fn4.length) // 1
console.log(fn5.length) // 0
剩余参数不计入 length
剩余参数不会被计入 length 的统计中:
function fn1(name, ...args) {}
console.log(fn1.length) // 1
计算结果
123['toString'] 访问的是 Number.prototype.toString 方法,该方法的 length 为 1(接受一个可选的 radix 参数)。
因此:123['toString'].length + 123 = 1 + 123 = 124
关键点
- 函数的
length属性表示必须传入的参数个数,即形参个数 - 只统计第一个具有默认值之前的参数
- 剩余参数(
...args)不计入length - 具有默认值的参数及其后面的参数都不计入
length
目录