我正在查看 Mozilla 开发人员页面上有关 map 功能的文档,并对其中一个示例有疑问。
这是开发页面的链接。我正在查看“一般使用 map ”示例。我还包含了以下代码:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
var map = Array.prototype.map;
var a = map.call('Hello World', function(x) { return x.charCodeAt(0); });
// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
首先,“一般”使用 map 是什么意思。我猜这与
var map = Array.prototype.map;
对我来说仍然是新事物之一是 JS 中的原型(prototype)。用我自己的话来说,我的理解是它可以用来改变函数的工作方式,并且它的工作方式是将类的功能添加到 JS。
无论如何, map 变量中存储的是什么?为什么他们现在可以将字符串传递给 map 函数的参数?在 map 上调用 map 函数而不是做类似的事情有什么意义:
var a = 'Hello World'.split('').map( function(x) { return x.charCodeAt(0); });
最佳答案
First off what do they mean by using map "generically".
“一般地使用 map”意味着在不是数组的对象上使用 Array.prototype.map()
。它适用于字符串“Hello World”,因为“Hello World”将返回一个长度,并且可以像数组一样进行迭代。
One of the things that is still new to me is prototype in JS
我喜欢将原型(prototype)视为“刚内置到此类中的东西”。例如,假设您正在制作一款涉及赛车的视频游戏。所有车辆都有能力“驾驶”和“停止”。您可以创建一个“车辆”类,并将“驱动”和“停止”方法保存到其原型(prototype)中,而不是制作数百辆车辆并一遍又一遍地输入它们的“驾驶”和“停止”方法。现在,当您创建“FastCar”时,您可以将其设为“Vehicle”的实例,这样就可以访问那些原型(prototype)“Drive”和“Stop”方法,而不必分别重写它们每一次。
what is this storing in the map variable?
您在上面发布的 map
变量只是引用 Array.prototype.map
所以它的较长形式不需要每次都输入。
How come they can now pass a string to the args of the map function
字符串未作为 map 函数的参数传递。相反,map 在字符串本身上被调用。
What is the point of calling the map function on map
var map
在你的帖子中实际上并没有调用 Array.prototype.map
,它需要在末尾加上括号才能真正像这样调用它:Array.prototype.map()
。
instead of doing something like
您提出的解决方案没有任何问题,但我认为文档向您展示了它的灵 active ,以及如何始终针对同一问题提供不同的解决方案。
关于javascript - 一般使用javascript map函数是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30514225/