问题描述
我正在学习编写代码的教程(我对这方面还很陌生),这个特殊的练习让我绞尽脑汁.参数如下:
I'm going through tutorials to code (I'm fairly new at this), and this particular exercise is racking my brain. Here are the parameters:
反转提供的字符串.您可能需要先将字符串转换为数组,然后才能反转它.你的结果必须是一个字符串.
这是我开始的代码:
function reverseString(str) {
return str;
}
reverseString('hello');
expect(reverseString('hello')).to.be.a('String');
expect(reverseString('hello')).to.equal('olleh');expected 'hello' to equal 'olleh'
expect(reverseString('Howdy')).to.equal('ydwoH');expected 'Howdy' to equal 'ydwoH'
expect(reverseString('Greetings from Earth')).to.equal('htraE morf sgniteerG');expected 'Greetings from Earth' to equal 'htraE morf sgniteerG'
有没有关于如何实现这一点的建议?
Any suggestions out there on how to accomplish this?
** 我知道我的问题是什么.教程站点的特定 IDE 使它变得混乱.显然,我打算实现列出的目标之一(并非我之前认为的所有目标都在一个脚本中).这是通过 return str.split( '' ).reverse( ).join( '' );
实现的.split 和 join 方法的参数起初也有点混乱.这个方法网上的教程大部分都是以分词为例,所以没意识到从
** I figured out what my issue was. The particular IDE of the tutorial site made it confusing. Apparently I was meant to hit one of the objectives listed (not all of them in one script as I previously thought). This was accomplished by return str.split( '' ).reverse( ).join( '' );
. The parameters for the split and join methods were a little confusing at first as well. Most online tutorials of this method use splitting words as an example, so I didn't realize going from
" "
到 ""
会改变这个过程,从颠倒单词到颠倒字母.
would change the process from reversing words to reversing letters.
推荐答案
数组有一个方法叫做 reverse( ).本教程暗示使用它.
Arrays have a method called reverse( ). The tutorial is hinting at using this.
要将字符串转换为字符数组(实际上它们只是单个字符串),您可以使用方法 split( ) 以空字符串作为分隔符.
To convert a string into an array of characters (in reality they're just single character strings), you can use the method split( ) with an empty string as the delimiter.
为了将数组转换回字符串,您可以使用方法 join( ) 再次以空字符串作为参数.
In order to convert the array back into a string, you can use the method join( ) again, with an empty string as the argument.
使用这些概念,您将找到反转字符串的常见解决方案.
Using these concepts, you'll find a common solution to reversing a string.
function reverseString(str) {
return str.split( '' ).reverse( ).join( '' );
}
这篇关于在 JS 中反转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!