Javascript _.reduce() exercise
Javascript _.reduce() exercise
请提供帮助;我正在努力解决这个问题:
编写一个函数,接受一组名称并祝贺它们。请确保使用_.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!"
相关文章:
- 对一个对象使用reduce可以返回一个没有't在数组中包含目标字母
- 节点中的Map Reduce
- 对于这种情况,函数Reduce CouchDB
- 我们可以用参数对象集合而不是原始数据来调用JavaScript collection.reduce()方法吗
- 解构javascript中的reduce函数
- 关于reduce在javascript中创建过滤器的说明
- 为什么 Array.prototype.reduce() 不接受 Map 对象作为初始值
- 在javascript中使用reduce对数组中的变量求和
- Map/Reduce给我NaN或错误的结果(由于null)
- Undercore reduce,关于备忘录
- Array.prototype.reduce的实际用途是什么
- MongoDB map/reduce,forEach不是一个函数
- 使用map/reduce计算总数
- Javascript作用域规则和mongo-map/reduce函数
- Javascript _.reduce() exercise
- 用函数重写reduce方法
- 有MongoDB的参考吗's map reduce javascript
- 试图了解如何使用_.reduce
- 如果数组中只有一个对象,则Lodash返回错误的reduce结果
- 使用JavaScript's Reduce从对象数组创建数组