How can I get following output when I pass following string in function as argument?
当我在函数中传递以下字符串作为参数时,如何获得以下输出?
-
input:
"Reverse this line"
输入:“反转此行”
-
output:
"esreveR siht enil"
输出:“esreveR siht enil”
this is my code
function reverseWords(string) {
var wordArray = string.split(" ");
var resultWordArray = [];
var requiredSentance;
wordArray.forEach(word => {
if (word == " ") {
var space = " ";
resultWordArray.push(space);
} else {
var SplittedWord = word.split("");
var reversedWordsLettersArray = [];
SplittedWord.forEach(letter => {
reversedWordsLettersArray.unshift(letter);
var reversedWord = reversedWordsLettersArray.join("");
resultWordArray.push(reversedWord);
})
}
})
var resultSentance = resultWordArray.join(" ");
console.log(resultSentance);
}
reverseWords("Reverse this line");
which is returning this as output:
这将作为输出返回:
"R eR veR eveR reveR sreveR esreveR t ht iht siht l il nil enil"
What am I missing here?
我在这里想念的是什么?
4 个解决方案
#1
6
Using your code specifically, you are very close with what you are trying to do. You just need to move the declaration of the reversedWord
variable out of the forEach
loop, update inside the forEach
loop, which will eventually be defined with the entire reversed word.
具体使用您的代码,您非常接近您要做的事情。您只需要将reverseWord变量的声明移出forEach循环,在forEach循环内更新,最终将使用整个反转字来定义。
function reverseWords(string) {
var wordArray = string.split(" ");
var resultWordArray = [];
var requiredSentance;
wordArray.forEach(word => {
if (word == " ") {
var space = " ";
resultWordArray.push(space);
} else {
var SplittedWord = word.split("");
var reversedWordsLettersArray = [];
var reversedWord; //define variable here
SplittedWord.forEach(letter => {
reversedWordsLettersArray.unshift(letter);
reversedWord = reversedWordsLettersArray.join("");
})
resultWordArray.push(reversedWord); // push it here
}
})
var resultSentance = resultWordArray.join(" ");
console.log(resultSentance);
}
reverseWords("Reverse this line");
#2
10
You can split the string into words and map through each word, splitting it into a character array and reverse the array, then join back the words into a single string. Like this:
您可以将字符串拆分为单词并映射每个单词,将其拆分为字符数组并反转数组,然后将单词连接回单个字符串。像这样:
string.split(' ').map(s => s.split('').reverse().join('')).join(' ')
To explain the code:
解释代码:
string.split(' ')
This line splits the whole string into array of words, "Reverse this line"
becomes ["Reverse", "this", "line"]
(note that the spaces are gone). Keep in mind that double spaces will be still split as a single space.
该行将整个字符串拆分为单词数组,“反向此行”变为[“反向”,“此”,“行”](注意空格已消失)。请记住,双空格仍将作为单个空格拆分。
Since we now have an array, you can iterate the whole string using the .map
function. It works similarly to how you've tried to use the .forEach
, with the difference that the .map
function will return a new array with modified values which are returned in each iteration of the .map
callback function. Make sure to return something, or the values will be undefined
! The arrow function from ES2015+ has implicit return as you see in the example above, but if you were to use => {...}
, the block needs an explicit return
statement to work.
由于我们现在有一个数组,你可以使用.map函数迭代整个字符串。它与您尝试使用.forEach的方式类似,区别在于.map函数将返回一个带有修改值的新数组,这些值在.map回调函数的每次迭代中返回。确保返回一些内容,否则值将不确定!正如您在上面的示例中所看到的,ES2015 +中的箭头函数具有隐式返回,但如果您使用=> {...},则块需要显式返回语句才能工作。
The code of the .map
function callback
.map函数回调的代码
s => s.split('').reverse().join('')
Receives a s
, which is a single word from the array above, splits the word by empty string, which is a workaround to split a string into characters. For example, "Reverse"
becomes ["R", "e", "v", "e", "r", "s", "e"]
. The .reverse()
function's name is quite descriptive, it just reverses the array. But be careful! It mutates the array, so if you call the .reverse()
function on a random array, it will be reversed from that line on. This could cause some issues if you're not careful. Lastly, the .join('')
puts the reversed array of characters back into a single string word.
接收一个s,它是上面数组中的单个单词,用空字符串分割单词,这是将字符串拆分为字符的解决方法。例如,“Reverse”变为[“R”,“e”,“v”,“e”,“r”,“s”,“e”]。 .reverse()函数的名称非常具有描述性,它只是反转数组。不过要小心!它会改变数组,所以如果在随机数组上调用.reverse()函数,它将从该行反转。如果你不小心,这可能会导致一些问题。最后,.join('')将反转的字符数组放回一个字符串单词中。
And finally the .join(' ')
at the end puts the mapped array, which now contains reversed words, back together with spaces in-between, similarly to how .join('')
puts the array of characters back into a single word.
最后,最后的.join('')将映射的数组(现在包含反转的单词)与中间的空格一起放回,类似于.join('')将字符数组放回一个单词中。
#3
1
Here's an interesting approach that doesn't require a call to .map()
, if you think outside the box a bit about the string processing:
这是一个有趣的方法,如果您在框外略微考虑字符串处理,则不需要调用.map():
function reverseWords(string, delimiter = ' ') {
return string
.split('').reverse().join('')
.split(delimiter).reverse().join(delimiter);
}
console.log(reverseWords('Reverse this line'));
If you reverse character-by-character on the first pass, you can then split the string by the word delimiter (in this case ' '
) and reverse the words to put them back in the original order on the second pass.
如果在第一遍中逐个字符地反转,则可以通过单词分隔符(在本例中为'')拆分字符串并反转单词以在第二遍中将它们放回原始顺序。
After benchmarking this approach, I've found that it is twice as fast as the currently accepted answer.
在对这种方法进行基准测试后,我发现它的速度是目前接受的答案的两倍。
Another nice feature about this function is that you can specify the word delimiter as the optional second argument:
关于此函数的另一个不错的功能是您可以将单词分隔符指定为可选的第二个参数:
function reverseWords(string, delimiter = ' ') {
return string
.split('').reverse().join('')
.split(delimiter).reverse().join(delimiter);
}
console.log(reverseWords('Reverse this line', '\t'));
#4
1
Here's a recursive method that just iterates once over the string:
这是一个递归方法,只在字符串上迭代一次:
function reverseWords(string){
return (function f(str, i, reversed){
if (!str[i])
return reversed;
if (str[i] == ' ')
return reversed + ' ' + f(str, i + 1, '');
return f(str, i + 1, str[i] + reversed);
})(string, 0, '');
}
console.log(reverseWords("Reverse this line"));
#1
6
Using your code specifically, you are very close with what you are trying to do. You just need to move the declaration of the reversedWord
variable out of the forEach
loop, update inside the forEach
loop, which will eventually be defined with the entire reversed word.
具体使用您的代码,您非常接近您要做的事情。您只需要将reverseWord变量的声明移出forEach循环,在forEach循环内更新,最终将使用整个反转字来定义。
function reverseWords(string) {
var wordArray = string.split(" ");
var resultWordArray = [];
var requiredSentance;
wordArray.forEach(word => {
if (word == " ") {
var space = " ";
resultWordArray.push(space);
} else {
var SplittedWord = word.split("");
var reversedWordsLettersArray = [];
var reversedWord; //define variable here
SplittedWord.forEach(letter => {
reversedWordsLettersArray.unshift(letter);
reversedWord = reversedWordsLettersArray.join("");
})
resultWordArray.push(reversedWord); // push it here
}
})
var resultSentance = resultWordArray.join(" ");
console.log(resultSentance);
}
reverseWords("Reverse this line");
#2
10
You can split the string into words and map through each word, splitting it into a character array and reverse the array, then join back the words into a single string. Like this:
您可以将字符串拆分为单词并映射每个单词,将其拆分为字符数组并反转数组,然后将单词连接回单个字符串。像这样:
string.split(' ').map(s => s.split('').reverse().join('')).join(' ')
To explain the code:
解释代码:
string.split(' ')
This line splits the whole string into array of words, "Reverse this line"
becomes ["Reverse", "this", "line"]
(note that the spaces are gone). Keep in mind that double spaces will be still split as a single space.
该行将整个字符串拆分为单词数组,“反向此行”变为[“反向”,“此”,“行”](注意空格已消失)。请记住,双空格仍将作为单个空格拆分。
Since we now have an array, you can iterate the whole string using the .map
function. It works similarly to how you've tried to use the .forEach
, with the difference that the .map
function will return a new array with modified values which are returned in each iteration of the .map
callback function. Make sure to return something, or the values will be undefined
! The arrow function from ES2015+ has implicit return as you see in the example above, but if you were to use => {...}
, the block needs an explicit return
statement to work.
由于我们现在有一个数组,你可以使用.map函数迭代整个字符串。它与您尝试使用.forEach的方式类似,区别在于.map函数将返回一个带有修改值的新数组,这些值在.map回调函数的每次迭代中返回。确保返回一些内容,否则值将不确定!正如您在上面的示例中所看到的,ES2015 +中的箭头函数具有隐式返回,但如果您使用=> {...},则块需要显式返回语句才能工作。
The code of the .map
function callback
.map函数回调的代码
s => s.split('').reverse().join('')
Receives a s
, which is a single word from the array above, splits the word by empty string, which is a workaround to split a string into characters. For example, "Reverse"
becomes ["R", "e", "v", "e", "r", "s", "e"]
. The .reverse()
function's name is quite descriptive, it just reverses the array. But be careful! It mutates the array, so if you call the .reverse()
function on a random array, it will be reversed from that line on. This could cause some issues if you're not careful. Lastly, the .join('')
puts the reversed array of characters back into a single string word.
接收一个s,它是上面数组中的单个单词,用空字符串分割单词,这是将字符串拆分为字符的解决方法。例如,“Reverse”变为[“R”,“e”,“v”,“e”,“r”,“s”,“e”]。 .reverse()函数的名称非常具有描述性,它只是反转数组。不过要小心!它会改变数组,所以如果在随机数组上调用.reverse()函数,它将从该行反转。如果你不小心,这可能会导致一些问题。最后,.join('')将反转的字符数组放回一个字符串单词中。
And finally the .join(' ')
at the end puts the mapped array, which now contains reversed words, back together with spaces in-between, similarly to how .join('')
puts the array of characters back into a single word.
最后,最后的.join('')将映射的数组(现在包含反转的单词)与中间的空格一起放回,类似于.join('')将字符数组放回一个单词中。
#3
1
Here's an interesting approach that doesn't require a call to .map()
, if you think outside the box a bit about the string processing:
这是一个有趣的方法,如果您在框外略微考虑字符串处理,则不需要调用.map():
function reverseWords(string, delimiter = ' ') {
return string
.split('').reverse().join('')
.split(delimiter).reverse().join(delimiter);
}
console.log(reverseWords('Reverse this line'));
If you reverse character-by-character on the first pass, you can then split the string by the word delimiter (in this case ' '
) and reverse the words to put them back in the original order on the second pass.
如果在第一遍中逐个字符地反转,则可以通过单词分隔符(在本例中为'')拆分字符串并反转单词以在第二遍中将它们放回原始顺序。
After benchmarking this approach, I've found that it is twice as fast as the currently accepted answer.
在对这种方法进行基准测试后,我发现它的速度是目前接受的答案的两倍。
Another nice feature about this function is that you can specify the word delimiter as the optional second argument:
关于此函数的另一个不错的功能是您可以将单词分隔符指定为可选的第二个参数:
function reverseWords(string, delimiter = ' ') {
return string
.split('').reverse().join('')
.split(delimiter).reverse().join(delimiter);
}
console.log(reverseWords('Reverse this line', '\t'));
#4
1
Here's a recursive method that just iterates once over the string:
这是一个递归方法,只在字符串上迭代一次:
function reverseWords(string){
return (function f(str, i, reversed){
if (!str[i])
return reversed;
if (str[i] == ' ')
return reversed + ' ' + f(str, i + 1, '');
return f(str, i + 1, str[i] + reversed);
})(string, 0, '');
}
console.log(reverseWords("Reverse this line"));