【发布时间】:2016-05-11 16:54:41
【问题描述】:
所以我最近一直在玩弄 CoffeeScript。到目前为止,从 JS 的过渡还算顺利,但现在我终于遇到了一个我真的想不通的问题。
我有这块 ES6:
function upcaseOddIndexes (arr, cha, ind) {
if (ind % 2 === 0) {
arr.push(cha.toUpperCase());
} else {
arr.push(cha);
}
return arr;
}
var string = "stringthing";
var upcasedString = string.split("")
.reduce((arr, cha, ind) => upcaseOddIndexes (arr, cha, ind), [])
.join("");
console.log(upcasedArray);
完成它的工作(返回一个新字符串,其中奇数索引处的字母大写)就好了。 upcaseOddIndexes 函数也没有问题。但是如何将空数组作为initialValue 传递给reduce()?
我最好的猜测是
.reduce(arr, cha, ind -> upcaseOddIndexes arr, cha, ind) []
这给了我
.reduce(arr, cha, ind(function() {
return upcaseOddIndexes(arr, cha, ind);
}))([])
这无济于事,因为arr is not defined。
我尝试添加更多括号、逗号等,但我总是遇到unexpected , 或类似的东西。
我已经对 Google 进行了很好的搜索,但到目前为止还没有找到答案。有this question 在这个话题上,但它并没有真正帮助。
提前非常感谢 =)
【问题讨论】:
-
从 ES6 到 CS 似乎是倒退了一步。
-
@FelixKling CS 编译为 ES6,所以没有多大意义
标签: javascript coffeescript ecmascript-6 reduce