当一个字符串被传递给一个带有返回语句的函数时,你如何在JavaScript中反转它,而不使用内置函数(.reverse(), . charat()等)?
当前回答
word.split('').reduce((acc, curr) => curr+""+acc)
其他回答
你不能将字符串反向,但你可以使用这个:
String.prototype.reverse = function() { 返回this.split (" ") .reverse () . join (" "); } var s = "ABCD"; S = S .reverse(); console.log(年代);
你可以尝试这样做。我相信还有重构的空间。我无法使用分裂函数。也许有人知道不分裂的方法。
代码设置,可以把它放在你的。js库
使用它的代码(有客户端代码,只是因为它在浏览器中测试过):
var sentence = "My Stack is Overflowing."
document.write(sentence.reverseLetters() + '<br />');
document.write(sentence.reverseWords() + '<br />');
代码片段:
String.prototype.aggregate = function(vals, aggregateFunction) { var temp = ''; for (var i = vals.length - 1; i >= 0; i--) { temp = aggregateFunction(vals[i], temp); } return temp; } String.prototype.reverseLetters = function() { return this.aggregate(this.split(''), function(current, word) { return word + current; }) } String.prototype.reverseWords = function() { return this.aggregate(this.split(' '), function(current, word) { return word + ' ' + current; }) } var sentence = "My Stack is Overflowing." document.write(sentence.reverseLetters() + '<br />'); document.write(sentence.reverseWords() + '<br />');
我想,这对你有用
function reverse(str){
str = str.split("").reverse().join("").split(" ").reverse().join(" ");
console.log(str)
}
function reverseWords(str) {
// Go for it
const invertirPalabra = palabra => palabra.split('').reverse().join('')
return str.split(' ').map(invertirPalabra).join(' ')
// con split convierto string en array de palabras, le paso ' '
// que es que me lo separe por espacios
// luego invierto cada palabra...
// y luego con join las uno separando por espacios
}
首先,使用array .from()将字符串转换为数组,然后使用array .prototype.reverse()将数组反向,然后使用array .prototype.join()将其转换为字符串。
const reverse = str => Array.from(str).reverse().join('');