FED9. Array.reduce
描述
请补全JavaScript代码,要求实现Array.reduce函数的功能且该新函数命名为"_reduce"。示例1
输入:
[1,2,3]._reduce((left, right) => left + right)
输出:
6
HTML/CSS/JavaScript 解法, 执行用时: 1688ms, 内存消耗: 77888KB, 提交时间: 2022-02-10
{"css":"","js":"","html":"<!DOCTYPE html>\n<html>\n <head>\n <meta charset=utf-8>\n </head>\n <body>\n \t\n <script type=\"text/javascript\">\n // 补全代码\n Array.prototype._reduce = function (f) {\n if(typeof f === 'function') {\n let res = 0;\n this.forEach(item=>{\n res = f(res,item);\n })\n return res;\n }\n }\n </script>\n </body>\n</html>","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 1691ms, 内存消耗: 77772KB, 提交时间: 2022-02-08
{"css":"","js":"","html":"<!DOCTYPE html>\n<html>\n <head>\n <meta charset=utf-8>\n </head>\n <body>\n \t\n <script type=\"text/javascript\">\n // 补全代码\n //fn里面有四个参数,分别是累加值,当前值,索引值,调用的数组\n //init是初始值\n Array.prototype._reduce = function(fn,init){\n if(typeof fn !== 'function'){\n throw new Error(`${fn} is not function`)\n }\n //reduce中的index是从0开始的,而没有传入初始值的时候,index是从1开始的\n let accumlator = init || this[0]\n let currentIndex = init ? 0 : 1\n for(currentIndex; currentIndex < this.length; currentIndex++){\n accumlator = fn(accumlator,this[currentIndex],currentIndex,this)\n }\n return accumlator\n }\n </script>\n </body>\n</html>","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 1691ms, 内存消耗: 77804KB, 提交时间: 2022-02-09
{"css":"","js":"","html":"<!DOCTYPE html>\n<html>\n <head>\n <meta charset=utf-8>\n </head>\n <body>\n \t\n <script type=\"text/javascript\">\n // 补全代码\n Array.prototype._reduce = function(fn,prev) {\n for(let i = 0 ; i < this.length ; i++) {\n if(prev === undefined) {\n //i+1 this的意思应该是 fn用到了啥参数 就传啥参数进去 比如这里用到了i+1 用到了this 就将这两个参数传入\n prev = fn(this[i],this[i+1],i+1,this)\n i++\n }else {\n prev = fn(prev,this[i],i,this)\n }\n }\n return prev\n }\n </script>\n </body>\n</html>","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 1735ms, 内存消耗: 77820KB, 提交时间: 2021-12-14
{"css":"","js":"","html":"<!DOCTYPE html>\n<html>\n <head>\n <meta charset=utf-8>\n </head>\n <body>\n \t\n <script type=\"text/javascript\">\n // 补全代码\n Array.prototype._reduce = function(fn,res = 0) {\n for(let v of this) {\n res = fn(res,v)\n }\n return res\n} \n </script>\n </body>\n</html>","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 1737ms, 内存消耗: 77812KB, 提交时间: 2022-01-22
{"css":"","js":"","html":"<!DOCTYPE html>\n<html>\n <head>\n <meta charset=utf-8>\n </head>\n <body>\n \t\n <script type=\"text/javascript\">\n // 补全代码\n const reduce = function (cb, init) {\n if (typeof cb != 'function') {\n throw new Error(`${cb} is not a function`);\n }\n // 累加器\n let accumulator = init || this[0];\n let currentIndex = init ? 0 : 1;\n for (currentIndex; currentIndex < this.length; currentIndex++) {\n accumulator = cb(accumulator, this[currentIndex], currentIndex, this);\n }\n return accumulator;\n }\n Array.prototype._reduce = reduce;\n </script>\n </body>\n</html>","libs":[]}