Javascript设置一个等于另一个变量的变量

时间:2014-01-09 14:21:20

标签: javascript reverse naming-conventions

我最近开始学习JavaScript,并且在变量命名方面遇到了一些问题。例如,这就是我通常在Ruby中所做的事情:

no_spaces = 'the gray fox'.gsub(/\s/, '')
=> "thegrayfox"
reversed = no_spaces.reverse()
=> "xofyargeht"

no_spaces
=> "thegrayfox"
reversed
=> "xofyargeht"

然而,同样的事情在JavaScript中不起作用。这是发生的事情:

var noSpaces = 'the gray fox'.replace(/\s/g, '').split('')
noSpaces
=> [ 't', 'h', 'e', 'g', 'r', 'a', 'y', 'f', 'o', 'x' ]
var reversed = noSpaces.reverse().join('')

noSpaces
=> [ 'x', 'o', 'f', 'y', 'a', 'r', 'g', 'e', 'h', 't' ]
reversed
=> 'xofyargeht'

在这里,似乎reverse()是罪魁祸首,但其他功能很可能会发生这种情况。我的代码中是否存在一个我没有意识到的问题,或者这只是关于JS的一个奇怪的问题?

3 个答案:

答案 0 :(得分:8)

reverse是一种变异方法,因此其ruby等效值为reverse!,而不是reverse。要保留原始数组,必须先克隆它:

> noSpaces = 'the gray fox'.replace(/\s/g, '').split('')
["t", "h", "e", "g", "r", "a", "y", "f", "o", "x"]
> reversed = noSpaces.slice(0).reverse()
["x", "o", "f", "y", "a", "r", "g", "e", "h", "t"]
> noSpaces
["t", "h", "e", "g", "r", "a", "y", "f", "o", "x"]

以下是MDN列出的所有数组mutator方法:

* pop()
* push()
* reverse()
* shift()
* sort()
* splice()
* unshift()

所有其他数组方法都是访问器。

答案 1 :(得分:2)

MDN是一个非常好的资源:

  

reverse方法将调用数组对象的元素转换到位,改变数组,并返回对数组的引用。

您需要阅读文档并确保了解它们的工作原理。

答案 2 :(得分:1)

您做的不同之处在于您将第一个变量初始化为。在Ruby中,您初始化为从中删除空格的字符串。在JavaScript中,您将其初始化为从您删除空格的字符串中的字符数组。

正确的JavaScript解决方案是:

var noSpaces = 'the gray fox'.replace(/\s/g, '')
noSpaces
=> "thegrayfox"
var reversed = noSpaces.split('').reverse().join('')

noSpaces
=> "thegrayfox"
reversed
=> 'xofyargeht'

实际上,正如thg435指出的那样,JavaScript reverse()方法会将数组更改到位,但是数组只是暂时的,所以它的改变并不重要(在这种情况下)。

注意:字符只是一个奇特的词我在这里用于JavaScript中长度为1的字符串。

相关问题