主题
函数
函数是什么?
函数的本质就是一个可以被调用的对象。
js
function sum1(a, b) {
return a + b
}
const sum2 = new Function('a', 'b', 'return a + b')函数表达式
js
function sayHi() {
// (1) 创建
alert('Hello')
}
let func = sayHi // (2) 复制
func() // Hello // (3) 运行复制的值(正常运行)!
sayHi() // Hello // 这里也能运行(为什么不行呢)定义函数
使用 arguments 对象
arguments 是 function 函数中的一个对象,用于 存储函数参数 的一个 类数组。 关于类数组,简单来说就是有着数组的特性,如有数组的 length,可以通过 index 来访问,但是却没有一些数组的方法,如 forEach()、map() …… 还有 DOM 对象数组,也是类数组。
js
console.log(arguments) //报错:arguments is not defined
function foo(n1, n2, n3) {
console.log(arguments) // Arguments(3) []
console.log(arguments.length) // 3
console.log(arguments[1]) // 2
}
foo(1, 2, 3) // 正确输出
const bar = () => {
console.log(arguments)
}
bar() // 报错:arguments is not definedjs
const foo = (...args) => {
// console.log(arguments) // arguments is not defined
console.log(args) //[1, 2, 3, 4, 5, 6]
}
foo(1, 2, 3, 4, 5, 6)
const bar = (n1, n2, ...args) => {
// console.log(arguments) // arguments is not defined
console.log(args) //[3, 4, 5, 6]
}
bar(1, 2, 3, 4, 5, 6)函数参数
有两种特殊的参数语法:默认参数 和 剩余参数。
默认参数
在 JavaScript 中,函数参数的默认值是 undefined。
js
function multiply(a, b) {
b = typeof b !== 'undefined' ? b : 1
return a * b
}
console.log(multiply(5)) // 5使用默认参数,在函数体的手动检查就不再必要了。
js
function multiply(a, b = 1) {
return a * b
}
console.log(multiply(5)) // 5剩余参数
剩余参数语法允许将不确定数量的参数表示为数组。
js
function multiply(multiplier, ...theArgs) {
return theArgs.map((x) => multiplier * x)
}
const arr = multiply(2, 1, 2, 3)
console.log(arr) // [2, 4, 6]