繁体   English   中英

Javascript 手册:`Array.prototype.includes()` 与 `Array.includes()`

[英]Javascript Manual: `Array.prototype.includes()` vs. `Array.includes()`

传入的“菜鸟”问题:

Javascript 在 arrays 上有一个includes方法。

看起来像:

Array.includes()

但是当我 go 到Javascript 手册来理解这种方法时,该页面上的标题(出于适当的技术原因,我意识到)是:

Array.prototype.includes()

Javascript 手册中的类似内容导致我根本不喜欢该手册(唉,我更依赖 W3Schools 而不是手册)。

但是,我真的很想学习解释手册。

所以,我的问题是:当实际用法看起来像: Array.includes()时,在文档中包含.prototype一词的意义是什么Array.prototype.includes() ) ?

(此外,如果有人对我如何提高对 Javascript 官方手册的理解有任何建议,我将不胜感激。)

所以,我的问题是:当实际用法看起来像: Array.includes()时,在文档中包含.prototype一词的意义是什么Array.prototype.includes() ) ?

重要的是实际用法看起来不像Array.includes()

 Array.includes();

这将引发TypeError: Array.includes is not a function因为Array.includes doesn't exist 访问不存在的属性计算结果为undefined ,因此Array.includes计算结果为undefined ,因此Array.includes()试图调用undefined ,就像 function 一样。

你可以在这里看到它的作用:

 console.log(Array.includes); undefined();

includes()方法是在Array全局 object 的原型上定义的,因此您可以在Array实例上调用它:

 [].includes();

可以看到[].includes是一个 function:

 console.log([].includes);

将此与Array.from进行比较,后者是在Array构造函数上定义的,而不是在Array原型上:

 console.log(Array.from);

你可以像这样使用它:

 console.log(Array.from({ length: 10 }, (_, num) => num << 2));

如果文档说Array.includes()你会像这样输入它(示例):

Array.includes(1);

相反,它说Array.prototype.includes()这意味着它不是在Array类型本身上调用的,而是在它的一个实例上调用的。 所以在这种情况下,你会写:

const numbers = [1, 2, 3];
numbers.includes(1);

JavaScript 通常被描述为基于原型的语言,原型就是 inheritance 在 JavaScript 中的工作方式。

原型是什么意思?

我们俩都同意 JavaScript 中的几乎所有内容都是 object (我说“几乎”,因为原语不被视为对象)很酷吗? 好的,现在 JS 中的每个 Object 都有一个名为 [[Prototype]] 的内部属性,内部我的意思是您不能像访问 JS 对象的属性一样直接访问它。

If we want to know the prototype of an object that we have created we either pass the instance of our object to Object.getPrototypeOf or through the __proto__ property of our object

例如:

let myArray = [1,2,3,4];
console.log(myArray.__proto__)
// Expected output: Array []

如果您扩展生成的 object,您会从上面的小代码片段中找到您所询问的 include 方法以及您在 JS 代码中创建的任何数组上可用的所有方法。 那是因为据说 myArray 和 JavaScript 中的所有 arrays 共享 Array.prototype 上定义的属性和方法!

现在,如果您再次查看上面代码片段中生成的 object 的方法,您会注意到一个名为构造函数的方法,它在 Array.prototype 上定义,就像 include 和其他方法一样

这就是在创建 JavaScript Array 对象的实例时调用的 function!

JavaScript 阵列 object 是什么意思? It's a global JavaScript object that is used in the construction of arrays, it's the Array in Array.prototype.includes() (you may call it a class for convenience buuuuut classes did not exist practically until the release of ES6...before then JS中没有class这样的东西)

因此,为了简单起见,将 Array 视为全局 object,所有 JS arrays 都是其实例,并考虑 Array。 proto因为它是封装了所有实例共享的属性和方法的原型!

关于文档,能够阅读文档并对所阅读的内容有相当的了解实际上是一件好事,所以我相信你很好!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM