rest 參數(shù)與 arguments 對象的區(qū)別:
1)rest 參數(shù)只包含那些沒有對應(yīng)形參的實(shí)參,而 arguments 對象包含了傳給函數(shù)的所有實(shí)參。
2)arguments對象不是一個(gè)真正的數(shù)組,而 rest 參數(shù)是真正的 Array 實(shí)例,也就是說你能夠在它上面直接使用所有的數(shù)組方法,比如 sort、map、forEach、pop
3)arguments對象還有一些附加的屬性 (如callee屬性)
arguments 對象
arguments 對象是所有非箭頭函數(shù)中的函數(shù)內(nèi)部變量(arguments 對象并不是在 ES6 中提出的)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</style>
</style>
</head>
<body>
<script>
function fn() {
console.log(arguments);
for (var i=0; i<arguments.length; i++) {
console.log(arguments[i]);
}
}
// Arguments(5) [1, 3, 5, 7, 9, callee: ?, Symbol(Symbol.iterator): ?]
// 1
// 3
// 5
// 7
// 9
fn(1,3,5,7,9);
</script>
</body>
</html>
rest 參數(shù)
rest 參數(shù)又叫剩余參數(shù)。它允許我們將一個(gè)或多個(gè)不定數(shù)量的實(shí)參表示為一個(gè)數(shù)組。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</style>
</style>
</head>
<body>
<script>
function fn(...args) {
console.log(args);
}
// (5) [1, 3, 5, 7, 9]
fn(1,3,5,7,9);
function f(a, b, ...args) {
console.log(args);
}
// (3) [5, 7, 9]
f(1,3,5,7,9);
// []
f(1,3);
</script>
</body>
</html>