一夺巩、arguments對象
01、函數(shù)里的arguments
對于一個普通函數(shù)fn乍构,函數(shù)內(nèi)部內(nèi)置了一個 arguments 對象甜无,當(dāng)用于接收實參的形參個數(shù)不確定時,可以用arguments接收哥遮。
function fn(){
console.log(arguments)
// [1, 2, 3, callee: ?, Symbol(Symbol.iterator): ?]
}
fn(1,2,3)
arguments展示形式是一個偽數(shù)組岂丘。
02、什么是偽數(shù)組
偽數(shù)組也叫類數(shù)組眠饮,并不是真正意義上的數(shù)組奥帘,是一組具有數(shù)組的length屬性以及下標(biāo),但是不具有數(shù)組的push君仆、pop翩概、reverse等方法的對象。
- 01. 具有l(wèi)ength屬性和下標(biāo):
function fn(){
console.log(arguments.length) // 3
console.log(arguments[1]) // 2
}
fn(1,2,3)
- 可以遍歷
function fn() {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]) // 1 2 3
}
}
fn(1, 2, 3)
- 不具有數(shù)組的 push , pop等方法
function fn() {
arguments.push(4)
// Uncaught TypeError: arguments.push is not a function
}
fn(1, 2, 3)
03返咱、箭頭函數(shù)里的arguments
箭頭函數(shù)里不能使用arguments獲取參數(shù)列表钥庇。
var fn = (a,b,c) => {
console.log(arguments) // 并不是參數(shù)列表
}
fn(1,2,3)
但是可以使用剩余參數(shù)獲取參數(shù)列表。
二咖摹、剩余參數(shù)
01评姨、簡介
剩余參數(shù)語法允許我們將一個不定數(shù)量的參數(shù)表示為一個數(shù)組。
function fn(...arguments) {
console.log(arguments) // [1,2,3]
}
fn(1, 2, 3)
02萤晴、可以與擴(kuò)展運算符一起使用
function fn(a, ...arguments) {
console.log(a) // a
console.log(arguments) // [2,3]
}
fn(1, 2, 3)
03吐句、剩余參數(shù)是真正的 Array
具有偽數(shù)組不具有的pop、push店读、sort方法等嗦枢。
function fn(...arguments) {
return arguments.sort()
}
console.log(fn(3, 2, 1)); // [1, 2, 3]
三、偽數(shù)組轉(zhuǎn)真正的數(shù)組
01屯断、Array.prototype.slice.call()
function fn() {
var args = Array.prototype.slice.call(arguments);
args.push(4)
return args
}
console.log(fn(1,2,3)); // [1,2,3,4]
02文虏、Array.from()
function fn() {
var args = Array.from(arguments);
args.push(4)
return args
}
console.log(fn(1,2,3)); // [1,2,3,4]
03、結(jié)構(gòu)賦值
function fn() {
let arr = [...arguments]
console.log(arr)
}
console.log(fn(1, 2, 3)); // [1, 2, 3]
四殖演、剩余參數(shù)和arguments對象之間的區(qū)別
1. 剩余參數(shù)只包含那些沒有對應(yīng)形參的實參氧秘,而 arguments 對象包含了傳給函數(shù)的所有實參。
2. 剩余參數(shù)是真正的數(shù)組趴久,arguments對象不是一個真正的數(shù)組丸相。
3. arguments對象還有一些附加的屬性。
arguments對象的屬性:
callee: ? fn()
length: 3
Symbol(Symbol.iterator): ? values()
arguments: (...)
caller: (...)
length: 0
name: "values"
__proto__: ? ()
[[Scopes]]: Scopes[0]
__proto__: Object
END
下一篇:7種不同函數(shù)內(nèi)的this指向問題
推薦閱讀: