当一个字符串被传递给一个带有返回语句的函数时,你如何在JavaScript中反转它,而不使用内置函数(.reverse(), . charat()等)?
当前回答
如果你不想使用任何内置功能。试试这个
var string = 'abcdefg';
var newstring = '';
for(let i = 0; i < string.length; i++){
newstring = string[i] += newstring;
}
console.log(newstring);
其他回答
你可以尝试这样做。我相信还有重构的空间。我无法使用分裂函数。也许有人知道不分裂的方法。
代码设置,可以把它放在你的。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 />');
以下是可以用来实现字符串反转的四种最常用方法
给定一个字符串,返回一个新字符串 字符顺序
问题的多种解决方案
//reverse('apple') === 'leppa'
//reverse('hello') === 'olleh'
//reverse('Greetings!') === '!sgniteerG'
// 1. First method without using reverse function and negative for loop
function reverseFirst(str) {
if(str !== '' || str !==undefined || str !== null) {
const reversedStr = [];
for(var i=str.length; i>-1; i--) {
reversedStr.push(str[i]);
}
return reversedStr.join("").toString();
}
}
// 2. Second method using the reverse function
function reverseSecond(str) {
return str.split('').reverse().join('');
}
// 3. Third method using the positive for loop
function reverseThird(str){
const reversedStr = [];
for(i=0; i<str.length;i++) {
reversedStr.push(str[str.length-1-i])
}
return reversedStr.join('').toString();
}
// 4. using the modified for loop ES6
function reverseForth(str) {
const reversedStr = [];
for(let character of str) {
reversedStr = character + reversedStr;
}
return reversedStr;
}
// 5. Using Reduce function
function reverse(str) {
return str.split('').reduce((reversed, character) => {
return character + reversed;
}, '');
}
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
}
函数反向(字符串) { Let arr = []; For (let char of string) { arr.unshift (char); } Let rev = arr.join(") 返回牧师 } Let result = reverse("hello") console.log(结果)
我知道这是一个已经被很好地回答过的老问题,但为了自娱自乐,我写了下面的反向函数,并想把它分享给其他人,以防它对其他人有用。它处理代理对和组合标记:
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字符编码的复杂性。