2016-10-31 6 views
5

私は自分でreduceを書きたいと思います。しかし、最後の4時間で、私はできませんでした。私自身の `reduce`関数を書くにはどうすればいいですか?

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 

はい、これはたくさんのトピックのようですが、回答が見つかりませんでした。私は何が欠けているのか、ここで間違っていますか?

+3

あなたは 'arguments'を使用する必要はありません - '関数(還元剤として明示的に宣言、はinitialValueは) ' – zerkms

+3

あなたは[MDNのポリフィル](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Polyfill)を見て撮影したことがありますか?それはあなたにいくつかのヒントを与えるはずです – UnholySheep

答えて

0

コード

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(fn, start){ 
 
    var result = start !== undefined ? start : this[0]; 
 
    for (var i = 0; i < this.length; i++) { 
 
    result = fn(result, this[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 
 
console.log(a.reduce(foo, ''), a.reduce2(foo, '')); 
 
console.log(a.reduce(foo, 'X'), a.reduce2(foo, 'X'));

+0

'add'の代わりに' foo'を渡そうとしましたか? – trincot

+0

いいえ、私は今はしませんでした。ありがとう、 ">あなたはまた、開始値の有無を区別する必要があります"私が逃したものを理解するのに役立ちます。 – Robiseb

+0

まだ問題があります。あなたがそれらを解決するとき、あなたのコードは私の答えと大きく異なることはありません。例えば、 'foo'の開始値として空でない文字列を渡してみてください。 ;-) – trincot

5

に基づいて、被検体内の配列は、引数として渡されたが、コンテキスト(this)がされていません。

ます。また、開始値の存在または不在を区別する必要があります。

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 (f, result) { 
 
    var i = 0; 
 
    if (arguments.length < 2) { 
 
    i = 1; 
 
    result = this[0]; 
 
    } 
 
    for(; i < this.length; i++) { 
 
    result = f(result, this[i], i, this); 
 
    } 
 
    return result; 
 
}; 
 
console.log(a.reduce(add), a.reduce2(add))   // 100 100 
 
console.log(a.reduce(add, 10), a.reduce2(add, 10)) // 110 110 
 
// extra test with foo: 
 
console.log(a.reduce(foo, 'X'), a.reduce2(foo, 'X')) // X10211356 X10211356

関連する問題