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

JS类数组对象、arguments #36

Open
conan1992 opened this issue Jun 23, 2020 · 0 comments
Open

JS类数组对象、arguments #36

conan1992 opened this issue Jun 23, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

类数组对象

拥有一个 length 属性和若干索引属性的对象

var obj = {
    0: 'a',
    1: 'b',
    2: 'c',
    length: 3
}

从读写看:和数组一样

console.log(obj[0], obj.length)//输出:"a", 3

但是数组有push方法,那么类数组对象呢

obj.push("d")//输出:index.html:29 Uncaught TypeError: obj.push is not a function

所以类数组就是类数组,和数组还是有差别的。那么如果想要让类数组调用数组的方法该怎么办呢?

调用数组方法

Array.prototype.push.call(obj, 'd');
console.log(obj)//输出: {0: 'a',1: 'b',2: 'c',3: 'd'length: 4}

类数组转数组

  • Array.prototype.map.call
var obj = {
    0: 'a',
    1: 'b',
    2: 'c',
    length: 3
}
function toArray(target){
    return Array.prototype.map.call(target, function(item){
        return item
    })
}
console.log(toArray(obj))//输出: ["a", "b", "c"]
  • Array.prototype.slice.call
function toArray(target){
    return Array.prototype.slice.call(target)
}
console.log(toArray(obj))//输出: ["a", "b", "c"]
  • Array.prototype.splice.call
function toArray(target){
    return Array.prototype.splice.call(target, 0)
}
console.log(toArray(obj))//输出: ["a", "b", "c"]
  • concat
function toArray(target){
    return Array.prototype.concat.apply([], target )
}
console.log(toArray(obj))//输出: ["a", "b", "c"]
  • Array.from
console.log(Array.from(obj))//输出: ["a", "b", "c"]

arguments

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

function foo(){
    console.log(arguments)
}
foo(1,2,3);

image

参数长度length

function foo(a,b,c){
    console.log("实参长度:"+arguments.length, "形参长度:"+foo.length)//实参长度:2 形参长度:3
}
foo(1,2);

callee属性

通过它可以调用函数自身。

var data = [];

for (var i = 0; i < 3; i++) {
    (data[i] = function () {
       console.log(arguments.callee.i) 
    }).i = i;
}

data[0]();//0
data[1]();//1
data[2]();//2

参数传递

// 使用 apply 将 foo 的参数传递给 bar
function foo() {
    bar.apply(this, arguments);
}
function bar(a, b, c) {
   console.log(a, b, c);
}

foo(1, 2, 3)

ES6

利用es6中的解构,将参数列表直接转成数组

function func(...arr) {
    console.log(arr, arguments); // [1, 2, 3]
}

func(1, 2, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant