Javascript _.reduce() exercise

Javascript _.reduce() exercise

本文关键字:exercise reduce Javascript      更新时间:2024-03-19

请提供帮助;我正在努力解决这个问题:

编写一个函数,接受一组名称并祝贺它们。请确保使用_.reduce作为函数的一部分。

输入:

['Steve', 'Sally', 'George', 'Gina']

输出:

'Congratulations Steve, Sally, George, Gina!'

到目前为止,我有一些东西,但不起作用:

var myArray = _.reduce(['Steve', 'Sally', 'George', 'Gina'], function(current, end) {
return 'Congratulations' + current + end;
});

你可以这样做:

var myArray = 'Congratulations ' + _.reduce(['Steve', 'Sally', 'George', 'Gina'], function(current, end) {
    return current + ', ' + end;
});
// "Congratulations Steve, Sally, George, Gina"

但reduce并不是最方便的工具,简单的join感觉更自然:

'Congratulations ' + ['Steve', 'Sally', 'George', 'Gina'].join(', ');

这是我的解决方案,它使用了reduce函数的所有参数。

var people = ["Steve", "Sally", "George", "Gina"];
people.reduce(
  function(prev, curr, currIndex, array){
    if(currIndex === array.length - 1){
      return prev + curr + "!";
    } else{
      return prev + curr + ", ";
    }
  }, "Congratulations ");
['Steve', 'Sally', 'George', 'Gina'].reduce(
    (a, b, i) => a + " " + b + (i <= this.length + 1 ? "," : "!"),
    "Congratulations"
)

这里是完整的reduce:

['Steve', 'Sally', 'George', 'Gina'].reduce( function(o,n, i, a){ var e=(i===(a.length-1))?"!":","; return o+n+e; }, "Congratulations ")

1) 你必须使用"祝贺"作为第一个元素reduce(f, initial)参见mdn

2) 有两种情况:a)没有到达最后一个元素,所以追加","b)else追加"!"。这是通过检查阵列i===(a.length-1) 长度的当前索引来完成的

// Input data
const names = ['Steve', 'Sally', 'George', 'Gina']
// Do the reduce
result = names.reduce((carry, name) => {
  return carry + " " + name
}, "Congratulations") + "!"
// Print-out the result
console.log(result)  // "Congratulations Steve Sally George Gina!"