javascript之类数组对象和arguments

138 阅读2分钟

1、类数组和数组的异同

类数组对象:拥有一个 length 属性和若干索引属性的对象

var array = ['name', 'age', 'sex'];

var arrayLike = {
    0: 'name',
    1: 'age',
    2: 'sex',
    length: 3
}

从读写、获取长度、遍历三个方面看看这两个对象

array[0] //name
arrayLike[0] //name

array[0] = 'new name';
arrayLike[0] = 'new name';

array.lenght;//3
arrayLike.lenght;//3


for(var i = 0, len = array.length; i < len; i++) {
    //todo
}
for(var i = 0, len = arrayLike.length; i < len; i++) {
    //todo
}

使用方法二者很像,但是类数组不能调用数组的方法 如

//报错
arrayLike.push('subname')

2、类数组调用数组方法

既然无法直接调用,我们可以用 Function.call 间接调用:

Array.prototype.join.call(arrayLike, '&');//name&age&sex

Array.prototype.join.map.call(arrayLike, function(item, i){
    //todo
})

3、类数组转数组

//es6写法
Array.from(arrayLike)
//apply
Array.prototype.concat.apply([], arrayLike)

//slice
Array.prototype.slice.call(arrayLike)
//splice
Array.prototype.splice.call(arrayLike, 0)

4、arguments

arguments 对象就是一个类数组对象。在客户端 JavaScript 中,一些 DOM 方法(document.getElementsByTagName()等)也返回类数组对象。

function foo(a,b,c) {
    console.log(arguments);
}
foo(1,2);

//得到arguments对象数据   
arguments = {
    0: 1
    1: 2
    callee: ƒ foo(a,b)
    length: 2
    Symbol(Symbol.iterator): ƒ values()
    __proto__: Object
}

length属性

//形参个数
foo.lenght //3

//实参个数
arguments.lenght //2

callee属性

arguments 对象的 callee 属性,通过它可以调用函数自身

arguments 和对应参数的绑定

function foo(name, age, sex, weight) {
    console.log(name);//name
    console.log(arguments[0]); //name
    
    name = 'new name';
    console.log(name);//new name
    console.log(arguments[0]);//new name

    arguments[1] = 'new age';
    console.log(age);//new age
    console.log(arguments[1]);//new age

    sex = 'new sex';
    console.log(sex);//new sex
    console.log(arguments[2]);//undefined

    arguments[3] = 'new weight';
    console.log(weight);//undefined
    console.log(arguments[3]);//new weight
}
foo('name', 'age');

传入的参数,实参和 arguments 的值会共享,当没有传入时,实参与 arguments 值不会共享。

除此之外,以上是在非严格模式下,如果是在严格模式下,实参和 arguments 是不会共享的。

5、应用

1)参数不定长

//es6不定参数
function func(...arguments) {
    console.log(arguments); // [1, 2, 3]
}

func(1, 2, 3);

2)函数柯里化

3)递归调用

4)函数重载

参考链接:github.com/mqyqingfeng…