gpt4 book ai didi

javascript - 对 Array.prototype.reduce 的 polyfill 感到困惑

转载 作者:行者123 更新时间:2023-11-29 10:58:54 30 4
gpt4 key购买 nike

<分区>

此代码是 Mozilla Developer Network 上提供的 Array.prototype.reduce 的 polyfill。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {
Array.prototype.map = function(callback /*, thisArg*/) {
var T, A, k
if (this == null) {
throw new TypeError('this is null or not defined')
}

var O = Object(this)
var len = O.length >>> 0

if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function')
}

if (arguments.length > 1) {
T = arguments[1]
}

A = new Array(len)
k = 0

while (k < len) {
var kValue, mappedValue

if (k in O) {
kValue = O[k]
mappedValue = callback.call(T, kValue, k, O)
A[k] = mappedValue
}
k++
}

return A
}
}

我不明白的是这两行

1.为什么不直接使用this

var O = Object(this)

2.有没有可能thisnull ,为什么需要下面这段代码?

if (this == null) {
throw new TypeError('this is null or not defined')
}

3.为什么我们需要k in O ?同时k < len , k总是在 O , 是无用条件吗?

if (k in O) {
kValue = O[k]
mappedValue = callback.call(T, kValue, k, O)
A[k] = mappedValue
}

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com