2

我知道 call 和 array.prototype.map.call() 函数的基本原理有两个参数,第一个是要使用的对象上下文,因为它在被调用函数内部,第二个是参数列表。但在 MDN 中,我找到了一个示例,其中通过调用方法使用 array.prototype.map 并将字符串作为第一个参数传递。

我想知道传递的字符串是如何在 map 函数中被操纵的。map 函数中没有 this 关键字。地图如何知道它是在字符串上调用的?

var map = Array.prototype.map;
var a = map.call('Hello World', function(x) { return x.charCodeAt(0); });
4

1 回答 1

6

该字符串在内部以以下格式表示:

String {0: "h", 1: "e", 2: "l", 3: "l", 4: "o", 5: " ", 6: "w", 7: "o", 8: "r", 9: "l", 10: "d", length: 11, [[PrimitiveValue]]: "hello world"}

因此,当它被传递给 map 时,它实际上被视为一个数组,因为它具有索引作为键和length属性。Array.prototype.map迭代它以返回数组,该数组在您使用该Function.prototype.call方法传入的字符串上调用。

new String('hello world')在控制台中尝试。

于 2016-07-08T05:27:28.703 回答