var array = ['name', 'age', 'sex'];es6
var arrayLike = {
0: 'name',
1: 'age',
2: 'sex',
length: 3
}數組
console.log(array[0]); // name
console.log(arrayLike[0]); // nameapp
array[0] = 'new name';
arrayLike[0] = 'new name';函數
console.log(array.length); // 3
console.log(arrayLike.length); // 3測試
for(var i = 0, len = array.length; i < len; i++) {
……
}
for(var i = 0, len = arrayLike.length; i < len; i++) {
……
}this
那類數組對象不可使用數組的方法prototype
var arrayLike = {0: 'name', 1: 'age', 2: 'sex', length: 3 }對象
Array.prototype.join.call(arrayLike, '&'); // name&age&sex索引
Array.prototype.slice.call(arrayLike, 0); // ["name", "age", "sex"]
// slice能夠作到類數組轉數組it
Array.prototype.map.call(arrayLike, function(item){
return item.toUpperCase();
});
// ["NAME", "AGE", "SEX"]
Arguments 對象只定義在函數體中,包括了函數的參數和其餘屬性。在函數體中,arguments 指代該函數的 Arguments 對象。
function foo(name, age, sex) {
console.log(arguments);
}
foo('name', 'age', 'sex')
Arguments對象的length屬性,表示實參的長度
function foo(b, c, d){
console.log("實參的長度爲:" + arguments.length)
}
console.log("形參的長度爲:" + foo.length)
foo(1)
// 形參的長度爲:3
// 實參的長度爲:1
rguments 對象的 callee 屬性,經過它能夠調用函數自身。
var data = [];
for (var i = 0; i < 3; i++) {
(data[i] = function () {
console.log(arguments.callee.i)
}).i = i;
}
data[0]();
data[1]();
data[2]();
// 0
// 1
// 2
function foo(name, age, sex, hobbit) {
console.log(name, arguments[0]); // name name
// 改變形參
name = 'new name';
console.log(name, arguments[0]); // new name new name
// 改變arguments
arguments[1] = 'new age';
console.log(age, arguments[1]); // new age new age
// 測試未傳入的是否會綁定
console.log(sex); // undefined
sex = 'new sex';
console.log(sex, arguments[2]); // new sex undefined
arguments[3] = 'new hobbit';
console.log(hobbit, arguments[3]); // undefined new hobbit
}
foo('name', 'age')
傳入的參數,實參和 arguments 的值會共享,當沒有傳入時,實參與 arguments 值不會共享
除此以外,以上是在非嚴格模式下,若是是在嚴格模式下,實參和 arguments 是不會共享的。
將參數從一個函數傳遞到另外一個函數
// 使用 apply 將 foo 的參數傳遞給 bar
function foo() {
bar.apply(this, arguments);
}
function bar(a, b, c) {
console.log(a, b, c);
}
foo(1, 2, 3)
function func(...arguments) {
console.log(arguments); // [1, 2, 3]
}
func(1, 2, 3);