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

Gav*_*cek 1 javascript reverse naming-conventions

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

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

no_spaces
=> "thegrayfox"
reversed
=> "xofyargeht"
Run Code Online (Sandbox Code Playgroud)

但是,同样的事情在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'
Run Code Online (Sandbox Code Playgroud)

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

geo*_*org 8

reverse是一种变异的方法,所以它的红宝石等价物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"]
Run Code Online (Sandbox Code Playgroud)

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

* pop()
* push()
* reverse()
* shift()
* sort()
* splice()
* unshift()
Run Code Online (Sandbox Code Playgroud)

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