JS小函数-反向顺序输出字符串
反向顺序输出字符串(单个单词不反向)
reverse('Hello World') === 'World Hello'
reverse('Hi There.') === 'There. Hi'
My Answer:
function reverse(string){
var mystr = string.split(' ');
var result = [];
for(var i =0;i<mystr.length;i++){
result[i] = mystr[mystr.length-1-i];
}
return result.join(' ');
}
Others:
1.
function reverse(string){
return string.split(' ').reverse().join(' ');
}
2.
reverse = s => s.split(' ').reverse().join(' ')
3.
function reverse(string){
var original = string;
var rev = original.split(' ').reverse().join(' ');
return rev;
}
4.
const reverse = words => words.split(' ').reverse().join(' ')
5.
function reverse(string){
return string.replace(/\s+/g, ' ').split(' ').reverse().join(' ');
}
6.
function reverse(string){
// validate input
if (typeof(string) !== 'string') throw new Error('reverse: parameter is not a string!');
// just use the dumb way out since it's jabbascripps
return string.split(' ').reverse().join(' ');
}
7.
function reverse(string){
if(typeof string === 'string')
{
var result = '';
string = string.split(' ');
for(var i = string.length ; i > 0; i--)
(i != 1 ? (result = result + string[i - 1] + ' '):(result = result + string[i - 1]));
}
return result;
}