我最近开始学习JavaScript,并在变量命名时遇到了一些问题。例如,这是我通常会在Ruby中执行的操作:Javascript设置一个变量等于另一个变量
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的怪异?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse –
啊,这样做更有意义。 (:我想我只是习惯于Ruby对大多数普通方法有独立的爆炸方法^^ 感谢您的领导和简单的解决方法!:D –
另外,感谢您的增变器方法列表!Green check has已经给出了 –