上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* @param {Function} callback
* @param {Object} context
* @return {void}
*/
Array.prototype.forEach = function(callback, context) {
}
/**
* const arr = [1,2,3];
* const callback = (val, i, arr) => arr[i] = val * 2;
* const context = {"context":true};
*
* arr.forEach(callback, context)
*
* console.log(arr) // [2,4,6]
*/
javascript 解法, 执行用时: 128 ms, 内存消耗: 63.2 MB, 提交时间: 2023-10-15 13:27:58
/**
* @param {Function} callback
* @param {Object} context
* @return {void}
*/
Array.prototype.forEach = function(callback, context) {
callback = callback.bind(context)
for (let [index, item] of this.entries()) {
callback(item, index, this)
}
}
/**
* const arr = [1,2,3];
* const callback = (val, i, arr) => arr[i] = val * 2;
* const context = {"context":true};
*
* arr.forEach(callback, context)
*
* console.log(arr) // [2,4,6]
*/
typescript 解法, 执行用时: 136 ms, 内存消耗: 70.5 MB, 提交时间: 2023-10-15 13:27:31
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Callback = (currentValue: JSONValue, index: number, array: JSONValue[]) => any
type Context = Record<string, JSONValue>
Array.prototype.forEach = function(callback: Function, context: any): void {
Array.from(this,(val,i)=>{
return callback.call(context,val,i,this)
})
// 或者
// for (let i = 0; i < this.length; i++) {
// callback.call(context, this[i], i, this);
// }
}
/**
* const arr = [1,2,3];
* const callback = (val, i, arr) => arr[i] = val * 2;
* const context = {"context":true};
*
* arr.forEach(callback, context)
*
* console.log(arr) // [2,4,6]
*/
javascript 解法, 执行用时: 108 ms, 内存消耗: 56.5 MB, 提交时间: 2023-10-15 13:26:53
/**
* @param {Function} callback
* @param {Object} context
* @return {void}
*/
Array.prototype.forEach = function(callback, context) {
for(let i = 0;i < this.length;i++){
callback.apply(context,[this[i],i,this])
}
}
/**
* const arr = [1,2,3];
* const callback = (val, i, arr) => arr[i] = val * 2;
* const context = {"context":true};
*
* arr.forEach(callback, context)
*
* console.log(arr) // [2,4,6]
*/