当一个字符串被传递给一个带有返回语句的函数时,你如何在JavaScript中反转它,而不使用内置函数(.reverse(), . charat()等)?
当前回答
我知道这是一个已经被很好地回答过的老问题,但为了自娱自乐,我写了下面的反向函数,并想把它分享给其他人,以防它对其他人有用。它处理代理对和组合标记:
function StringReverse (str)
{
var charArray = [];
for (var i = 0; i < str.length; i++)
{
if (i+1 < str.length)
{
var value = str.charCodeAt(i);
var nextValue = str.charCodeAt(i+1);
if ( ( value >= 0xD800 && value <= 0xDBFF
&& (nextValue & 0xFC00) == 0xDC00) // Surrogate pair)
|| (nextValue >= 0x0300 && nextValue <= 0x036F)) // Combining marks
{
charArray.unshift(str.substring(i, i+2));
i++; // Skip the other half
continue;
}
}
// Otherwise we just have a rogue surrogate marker or a plain old character.
charArray.unshift(str[i]);
}
return charArray.join('');
}
感谢Mathias、Punycode和其他各种参考资料,让我了解了JavaScript字符编码的复杂性。
其他回答
这样的事情应该遵循最佳实践:
(function(){ 'use strict'; var str = "testing"; //using array methods var arr = new Array(); arr = str.split(""); arr.reverse(); console.log(arr); //using custom methods var reverseString = function(str){ if(str == null || str == undefined || str.length == 0 ){ return ""; } if(str.length == 1){ return str; } var rev = []; for(var i = 0; i < str.length; i++){ rev[i] = str[str.length - 1 - i]; } return rev; } console.log(reverseString(str)); })();
String.prototype.reverse_string=function() {return this.split("").reverse().join("");}
or
String.prototype.reverse_string = function() {
var s = "";
var i = this.length;
while (i>0) {
s += this.substring(i-1,i);
i--;
}
return s;
}
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
}
word.split('').reduce((acc, curr) => curr+""+acc)
//recursive implementation
function reverse(wrd) {
const str =wrd[0]
if(!wrd.length) {
return wrd
}
return reverse(wrd.slice(1)) + str
}