简体   繁体   English

CoffeeScript中的reduce() - 如何传递默认值?

[英]reduce() in CoffeeScript - how do I pass a default value?

So I've been toying around with CoffeeScript a bit recently. 所以我最近一直在玩弄CoffeeScript。 So far the transition from JS has been rather smooth, but now I've finally run into a problem I really can't figure out. 到目前为止,JS的过渡相当顺利,但现在我终于遇到了一个我无法弄清楚的问题。

I've got this piece of ES6: 我有这个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);

which does its job (returning a new string with the letters at odd indexes uppercased) just fine. 它做了它的工作(返回一个新的字符串,其中奇数索引上的字母大写)就好了。 The upcaseOddIndexes function is no problem either. upcaseOddIndexes函数也没问题。 But how do I pass the empty array as the initialValue to reduce() ? 但是如何将空数组作为initialValue传递给reduce()

My best guess was 我最好的猜测是

.reduce(arr, cha, ind -> upcaseOddIndexes arr, cha, ind) []

which gives me 这给了我

.reduce(arr, cha, ind(function() {
  return upcaseOddIndexes(arr, cha, ind);
 }))([])

and that's going nowhere, since arr is not defined . 而且这无处可去,因为arr is not defined

I've tried adding more parens, commas and whatnot, but I always meet with unexpected , or something similar. 我已经尝试添加更多的parens,逗号和诸如此类的东西,但我总是遇到unexpected ,或类似的东西。

I've already had a good rummage around Google, but haven't found an answer so far. 我已经在谷歌周围进行了很好的翻找,但到目前为止还没有找到答案。 There's this question on the topic, but it didn't really help. 这个问题上的话题,但它并没有真正的帮助。

Thanks a lot in advance =) 非常感谢提前=)

You can reduce (arr, cha, ind) => upcaseOddIndexes (arr, cha, ind) to upcaseOddIndexes : 你可以减少(arr, cha, ind) => upcaseOddIndexes (arr, cha, ind)upcaseOddIndexes

string = "stringthing"
upcasedString = string
.split ""
.reduce upcaseOddIndexes, []
.join ""

That is converted to 那转换为

var string, upcasedString;

string = "stringthing";

upcasedString = string.split("").reduce(upcaseOddIndexes, []).join("");

or without reduction: 或不减少:

string = "stringthing"
upcasedString = string
.split ""
.reduce (arr, cha, ind) ->
  upcaseOddIndexes arr, cha, ind
, []
.join ""

That is converted to 那转换为

var string, upcasedString;

string = "stringthing";

upcasedString = string.split("").reduce(function(arr, cha, ind) {
  return upcaseOddIndexes(arr, cha, ind);
}, []).join("");

You need to specify the comma at the end of the call to reduce : 您需要在调用结束时指定逗号以reduce

.reduce ((arr, cha, ind) ->
  upcaseOddIndexes arr, cha, ind
), []

You'll find a Javascript to Coffeescript converter here 你会在这里找到一个Javascript to Coffeescript转换器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM