arguments 是一個(gè)對(duì)應(yīng)于傳遞給函數(shù)的參數(shù)的類數(shù)組對(duì)象。
什么是類數(shù)組呢?
類似于Array,但除了length屬性和索引元素之外沒(méi)有任何Array屬性。但是類數(shù)組可以被轉(zhuǎn)換為真正的數(shù)組。
var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
const args = Array.from(arguments);
const args = [...arguments];
arguments的使用
- length屬性表示實(shí)參的確切個(gè)數(shù)
- 可以通過(guò)數(shù)組索引的方式獲取單個(gè)參數(shù)的值
- 作為函數(shù)參數(shù)的別名(非嚴(yán)格模式)
function assert(bol, cons) {
if(bol) {
console.log(cons)
}
}
function whatever(a,b,c) {
// 值的準(zhǔn)確性校驗(yàn)
assert(a === 1, 'the value of a is 1')
assert(b === 2, 'the value of b is 2')
assert(c === 3, 'the value of c is 3')
// 共傳入 5 個(gè)參數(shù)
assert(arguments.length === 5, 'we have passed in 5 parameters')
// 驗(yàn)證傳入的前3個(gè)參數(shù)與函數(shù)的3個(gè)形參匹配
assert(arguments[0] === a, 'the first argument is assigned to a')
assert(arguments[1] === b, 'the second argument is assigned to b')
assert(arguments[2] === c, 'the third argument is assigned to c')
// 驗(yàn)證額外的參數(shù)可以通過(guò)參數(shù) arguments 獲取
assert(arguments[3] === 4, 'can access the fourth argument')
assert(arguments[4] === 5, 'can access the fifth argument')
// 別名
assert(a === 1, 'the a is 1')
assert(arguments[0] === 1, 'the first argument is 1')
arguments[0] = 666
assert(a === 666, 'now, the a is 666')
assert(arguments[0] === 666, 'now, the first argument is 666')
a = 999
assert(a === 999, 'now, the a is 999')
assert(arguments[0] === 999, 'now, the first argument is 999')
}
whatever(1,2,3,4,5)