我知道我们不能在字符串上使用Array.prototype.map
const str = 'MY NAME IS USER';
const result = str.map(c => c); // "Uncaught TypeError: str.map is not a function"
console.log(result);
这将导致错误状态:
"Uncaught : str.map不是函数“
但是今天我遇到了一个代码片段,在这里我可以在call Array.prototype上使用strings
const str = 'MY NAME IS USER';
const x = Array.prototype.map
.call(str, (c, i) => {
if (str.indexOf(c, i + 1) == -1 && str.lastIndexOf(c, i - 1) == -1)
return c;
})
.join('');
console.log(x);
在这个片段中,我无法了解Array.prototype.map 是如何调用 string str.的
发布于 2022-09-12 10:13:35
对象方法与this一起工作。map函数的实现类似于:
function map(cb) {
var r = [];
for (var i = 0; i < this.length; i++) {
r.push(cb(this[i]));
}
return r;
}使用.call调用函数时,可以决定this上下文应该是什么。尽管数组方法中的this通常是一个数组,但您在这里要重写它。以及实现map的方式--它如何使用this-happens来处理数组和字符串。
https://stackoverflow.com/questions/73687621
复制相似问题