Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript深入之类数组对象与arguments #12

Open
huiyiwanan opened this issue Jan 17, 2023 · 0 comments
Open

JavaScript深入之类数组对象与arguments #12

huiyiwanan opened this issue Jan 17, 2023 · 0 comments
Labels
Javascript 深入系列 Improvements or additions to documentation

Comments

@huiyiwanan
Copy link
Owner

huiyiwanan commented Jan 17, 2023

类数组对象

多为的类数组对象:

属性和若干索引属性的对象

举个例子:

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

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

为一探类数组和数组的区别究竟,我们从读取、获取长度、遍历三个方便入手

读写

console.log(array[0]); // name
console.log(arrayLike[0]); // name

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++) {
    ……
}

是不是很像?

那类数组对象可以使用数组的方法吗?比如:
arrayLike.push('4');

然而上述代码会报错: arrayLike.push is not a function

所以终归还是类数组呐……

调用数组方法

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可以做到类数组转数组

Array.prototype.map.call(arrayLike, function(item){
    return item.toUpperCase();
}); 
// ["NAME", "AGE", "SEX"]

类数组转数组

var arrayLike = {0: 'name', 1: 'age', 2: 'sex', length: 3 }
// 1. slice
Array.prototype.slice.call(arrayLike); // ["name", "age", "sex"] 
// 2. splice
Array.prototype.splice.call(arrayLike, 0); // ["name", "age", "sex"] 
// 3. ES6 Array.from
Array.from(arrayLike); // ["name", "age", "sex"] 
// 4. apply
Array.prototype.concat.apply([], arrayLike)

本文重点 - Arguments

Arguments 对象只定义在函数体中,包括了函数的参数和其他属性。在函数体中,arguments 指代该函数的 Arguments 对象。

function foo(name, age, sex) {
    console.log(arguments);
}

foo('name', 'age', 'sex')

长度

实参长度

callee属性

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

应用

如果要总结这些场景的话,暂时能想到的包括:

  1. 参数不定长
  2. 函数柯里化
  3. 递归调用
  4. 函数重载
    ...

下一篇文章

JavaScript深入至创建对象的多种方法以及优缺点

@huiyiwanan huiyiwanan added the Javascript 深入系列 Improvements or additions to documentation label Jan 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Javascript 深入系列 Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant