Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 运行for循环时,在coffeescript中哪个更好/更高效?_Javascript_Loops_Coffeescript - Fatal编程技术网

Javascript 运行for循环时,在coffeescript中哪个更好/更高效?

Javascript 运行for循环时,在coffeescript中哪个更好/更高效?,javascript,loops,coffeescript,Javascript,Loops,Coffeescript,用javascript编写以下函数有两种功能等效的方法,哪一种更好或更有效,为什么 (str) -> s = 0 for i in [0...str.length] s += str.charCodeAt i s 或 旁白:你能推荐其他的方法吗 编辑:根据JSPerf,第一个更快:-这是为什么 第一种更优雅,效率更高。第二个不必要地将字符串的每个字符复制到单独的字符串中,然后再将其转换为您熟悉的charCode?Coffeescript+一起工作真是太棒了。您可以使

用javascript编写以下函数有两种功能等效的方法,哪一种更好或更有效,为什么

(str) ->
  s = 0
  for i in [0...str.length]
    s += str.charCodeAt i 
  s

旁白:你能推荐其他的方法吗


编辑:根据JSPerf,第一个更快:-这是为什么

第一种更优雅,效率更高。第二个不必要地将字符串的每个字符复制到单独的字符串中,然后再将其转换为您熟悉的
charCode

?Coffeescript+一起工作真是太棒了。您可以使用ECMAScript 5上定义的本机
数组#reduce
,也可以使用下划线函数。第一个例子:

(s.charCodeAt(0) for s in "hello").reduce((acc, x) -> acc + x) # 532 

(在我的机器上)大约快一微秒,我会告诉你。。。(0.533ms vs 1.64ms)我最初想知道,获取字符串中某个位置的字符代码的时间是否会随着字符串长度的增加而增加,但现在想起来,如果有,与为每个字符创建单个字符串所需的时间相比,差异可以忽略不计。谢谢!:)
(s.charCodeAt(0) for s in "hello").reduce((acc, x) -> acc + x) # 532