通过调用字符串使用 array.prototype.map

use array.prototype.map via call on a string

我知道 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); });

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

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"}

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

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