AL-*_*ami 1 javascript call array.prototype.map
我知道call和array.prototype.map.call()函数的基础带有两个参数,第一个是要使用的对象上下文,因为这是在被调用函数内部,第二个是参数列表。但是在MDN中,我找到了一个示例,其中通过调用方法使用array.prototype.map并将字符串作为第一个参数传递。
我想知道传递的字符串如何在map函数中被操纵。map函数内没有此关键字。映射如何知道它是在字符串上调用的?
var map = Array.prototype.map;
var a = map.call('Hello World', function(x) { return x.charCodeAt(0); });
Run Code Online (Sandbox Code Playgroud)
该字符串在内部以以下格式表示:
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"}
Run Code Online (Sandbox Code Playgroud)
因此,当将其传递给map时,实际上将其视为数组,因为它具有索引作为键和length属性。Array.prototype.map对其进行迭代以返回数组,该数组在使用Function.prototype.call方法传递的字符串上调用。
new String('hello world')在控制台中尝试。