【问题标题】:Swapping array elements in coffeescript在咖啡脚本中交换数组元素
【发布时间】:2013-05-29 00:01:46
【问题描述】:

我正在学习coffeescript并编写了以下函数来反转给定的单词:

reverse = (word) ->
 if word.length is 0
     return "empty string"
 if word.length is 1
     return word
 left = 0
 right = word.length-1
 while left < right
     swap(word, left, right)
     #[word[left], word[right]] = [word[right], word[left]]
     left++
     right--
 return word

swap = (word, left, right) ->
 console.log "#{word[left]} #{word[right]}"
 temp = word[left]
 word[left] = word[right]
 word[right] = temp
 console.log "#{word[left]} #{word[right]}"

console.log reverse("coffeescript")

但它不起作用。在交换函数本身中,两个索引处的字符不会交换位置。我错过了什么?

【问题讨论】:

  • 我的答案正是使用 .split("") 将字符串转换为 char 数组。

标签: arrays string coffeescript swap


【解决方案1】:

问题可能在于 Javascript 中的字符串是不可变的,因此您不能更改它们。

另一种反转字符串的方法是

 "coffeescript".split("").reverse().join ""

来自rosettacode.org

【讨论】:

  • 啊,不敢相信我忘记了字符串是不可变的。谢谢!
【解决方案2】:

另一个反转字符串的选项是 CoffeeScript:

(c for c in 'coffeescript' by -1).join ''

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 2015-09-12
    • 2015-02-13
    相关资源
    最近更新 更多