js笔记——类数组

it2022-05-05  122

类数组

引入: function test() { console.log(arguments); // Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ] arguments.push(4); // 报错:Uncaught TypeError: arguments.push is not a function } test(1, 2, 3);

说明arguments可以当做数组来使用,但是没有数组中的一些方法

定义:如果一个对象的属性为索引(数字)属性,而且具有length属性,就称为类数组。类数组实际上是一个对象类数组中可以自定义数组中的方法,以便于使用 var obj = { "0": 1, "1": 2, "2": 3, "length":3, "push": Array.prototype.push } console.log(obj); console.log(obj[0]); obj.push(4); console.log(obj);

运行结果:

例题:(来源alibaba)

var obj = { "2": "a", "3": "b", "length": 2, "push": Array.prototype.push } obj.push('c'); obj.push('d'); console.log(obj); // {2: "c", 3: "d", length: 4, push: ƒ}

因为在Array.prototype中,push的实现为:

Array.prototype.push = function (target) { this[this.length] = target; this.length++; }

最新回复(0)