मैं अपने आप से reduce
लिखना चाहता हूं। लेकिन पिछले 4 घंटों में, मैं नहीं कर सका।मैं अपना खुद का 'कम करें' फ़ंक्शन कैसे लिखूं?
var a = [10, 21, 13, 56];
function add(a, b) { return a + b }
function foo(a, b) { return a.concat(b) }
Array.prototype.reduce2 = function() {
// I do not understand how to handle the function of the inlet
// I know that I should use arguments, but I don't know how many arguments there will be
var result = 0;
for(var i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
};
console.log(a.reduce(add), a.reduce2(add)) // 100 100
console.log(a.reduce(add, 10), a.reduce2(add, 10)) // 110 110
हाँ, मुझे पता है कि यह बहुत सारे विषयों की तरह लगता है, लेकिन मुझे जवाब नहीं मिला। मैं क्या खो रहा हूँ, या यहाँ गलत कर रहा हूँ?
आप' उपयोग करने के लिए arguments' की जरूरत नहीं है:
तुम भी उपस्थिति या शुरू मूल्य के अभाव के बीच अंतर करने की जरूरत है , प्रारंभिक वैल्यू) ' – zerkms
क्या आपने [एमडीएन पर पॉलीफिल] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Polyfill) पर एक नज़र डाली है? आपको कुछ संकेत देना चाहिए – UnholySheep