gpt4 book ai didi

javascript - 为什么 push 方法适用于对象?

转载 作者:行者123 更新时间:2023-11-30 15:38:00 25 4
gpt4 key购买 nike

为什么“推送方法”适用于对象?该机制如何运作?

function MyArray() { }
MyArray.prototype = [];

var arr = new MyArray();
arr.push(1, 2, 3);
console.log(arr); // [1, 2, 3] in Chrome

enter image description here

对不起我的英语。谢谢!

最佳答案

MyArray 返回一个对象,即使在 Chrome 中也是如此,并使用 Array 的方法, 通过指定 prototypal inheritance . MyArray 实例的结果仍然是一个对象,而不是数组。

function MyArray() { }
MyArray.prototype = [];

var arr = new MyArray();
arr.push(1, 2, 3);
console.log(arr); // { 0: 1, 1: 2, 2: 3, length: 3 }
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // false
console.log(arr instanceof Array); // true
console.log(arr instanceof MyArray); // true

关于javascript - 为什么 push 方法适用于对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41228266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com