-
-
Notifications
You must be signed in to change notification settings - Fork 230
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Array.prototype.map #11
Comments
Array.prototype._map = function (cb, thisBinding) {
// 排除回调非函数情况
if (typeof cb !== "function") {
throw new TypeError(`${cb} is not a function`);
}
// 排除this为非可迭代对象情况
if (this == null || typeof this[Symbol.iterator] !== "function") {
throw new TypeError(`${this} is not a iterable`);
}
// 将可迭代对象转换成数组
const array = [...this];
const result = [];
// 执行遍历并回调
for (let i = 0; i < array.length; i++) {
result.push(cb.call(thisBinding, array[i], i, this));
}
return result;
}; |
Array.prototype._map = function (callback, objThis) {
if (typeof callback !== "function") {
throw new TypeError("callback type error!");
}
const res = [];
for (let i = 0; i < this.length; ++i) {
res.push(callback.call(objThis, this[i], i, this));
}
return res;
}; |
|
Array.prototype.map = function (callback) {
const res = [];
for (let i = 0; i < this.length; i++) {
res.push(callback(this[i], i, this));
}
return res;
}; |
Array.prototype.map = function(callback, thisArg) {
var result = [];
for (var i = 0; i < this.length; i++) {
result.push(callback.call(thisArg, this[i], i, this));
}
return result;
} |
|
Array.prototype.mymap = function (callback, thisArg) {
const res = [];
for (let i = 0; i < this.length; i++) {
res.push(callback.call(thisArg, this[i], i, this));
//回调函数默认的this为undefined,thisArg作为回调函数的this
}
return res;
};
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
console.log(
arr1.mymap(function (item, index, arr) {
return 2 * this[index];
}, arr2)
); //[ 8, 10, 12 ] |
Array.prototype.map = function (cb) {
const res = []
for (let i = 0; i < this.length; i++) {
res.push(cb(this[i], i, this))
}
return res
}
let arr = [1, 2, 3]
let res = arr.map((item, index, arr) => {
return item + 1
})
console.log(res); |
Array.prototype._map = function(cb) {
const result = [];
for(let i=0; i<this.length; i++) {
result.push(cb(this[i], i, this))
}
return result;
} |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: