en.javascript.info/1-js/6-objects-more/6-call-apply/1-rewrite-sum-arguments/solution.md
2015-03-10 12:36:58 +03:00

31 lines
694 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Первый вариант
```js
//+ run
function sumArgs() {
// скопируем reduce из массива
arguments.reduce = [].reduce;
return arguments.reduce(function(a, b) {
return a + b;
});
}
alert( sumArgs(4, 5, 6) ); // 15
```
# Второй вариант
Метод `call` здесь вполне подойдёт, так как требуется вызвать `reduce` в контексте `arguments` с одним аргументом.
```js
//+ run
function sumArgs() {
// запустим reduce из массива напрямую
return [].reduce.call(arguments, function(a, b) {
return a + b;
});
}
alert( sumArgs(4, 5, 6) ); // 15
```