Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

6.arguments 参数理解 #17

Open
wl05 opened this issue May 10, 2019 · 0 comments
Open

6.arguments 参数理解 #17

wl05 opened this issue May 10, 2019 · 0 comments

Comments

@wl05
Copy link
Owner

wl05 commented May 10, 2019

javascript 中函数的arguments 是一个类似数组对象

属性

1. length属性

arguments 的length属性代表的是函数实际接收的参数,如果想获取函数期望获取的参数可以使用函数名.length来获取。

function demo(a, b, c) {
  var t = arguments.length
  var e = demo.length
  console.log(t)
  console.log(e)
}

demo(1, 2)
demo(1, 2, 3)
demo(1, 2, 3, 4)

运行结果:

2. callee属性

arguments.caller 属性指向函数本身

function demo(a, b, c) {
  console.log(arguments.callee)
}
demo()

运行结果:

3. caller属性

arguments.callee 指向调用当前函数的函数

function a() {
  if (a.caller) {
    var caller = a.caller.toString()
    console.log(caller)
  } else {
    console.log('none')
  }
}

function b() {
  a()
}

function c() {
  b()
}

a()
b()
c()

运行结果:

转换成数组

arguments对象不是一个 Array,它是一个类数组对象,它除了length属性外没有其他的数组属性和方法,但是我们可以通过以下方法将arguments对象转换成一个真正的数组

var args = Array.prototype.slice.call(arguments)
var args = [].slice.call(arguments)
var args = Array.from(arguments)
var args = [...arguments]
var args = (
arguments.length === 1 ?
  [arguments[0]] :
  Array.apply(null, arguments)
)
var args = Array.slice(arguments)

应用

1. 利用arguments.callee 实现递归调用

var demo = (function(num) {
  if (num <= 1) {
    return 1
  } else {
    return num * arguments.callee(num - 1)
  }
})(5)
console.log(demo)

运行结果:

2. 实现方法的重载,参数不定长

我们可以根据传入参数的数量的不同做不同的操作。

function demo() {
  var length = arguments.length
  for (var i = 0; i < length; i++) {
    if (typeof arguments[i] !== 'number') return
  }
  switch (length) {
    case 1:
      console.log('操作1')
      break
    case 2:
      console.log('操作2')
      break
    case 3:
      console.log('操作3')
      break
  }
}
demo(1)
demo(1, 2)
demo(1, 2, 3)

参考资料

  1. JavaScript深入之类数组对象与arguments
@wl05 wl05 changed the title arguments 参数理解 1.arguments 参数理解 Jan 9, 2020
@wl05 wl05 changed the title 1.arguments 参数理解 6.arguments 参数理解 Jan 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant