Js字符串反转

最开始的思路是,先把字符串分割,然后倒序拼接成一个新的字符串。于是有了

方法一:

复制代码
var name = "My city is WH";
var nameArr = name.split('');
var result=[];
var resultStr = '';
for (var i = 0, l = nameArr.length; i < l; i++) {
    result.unshift(nameArr[i]);

}
for (var i = 0, l = result.length; i < l; i++) {
    resultStr += result[i];
}
console.log(resultStr);  // HW si ytic yM
复制代码

 

方法二:reverse(),join()

var name = "My city is WH";
var resultStr = name.split('').reverse().join(''); 
console.log(resultStr);  // HW si ytic yM

 

方法三: charAt()

复制代码
var name = "My city is WuHan";
var nameArr = name.split('');
var resultStr = '';
for (var i = nameArr.length-1; i >= 0; i--) {
    resultStr += name.charAt(i);
}
console.log(resultStr); // naHuW si ytic yM
posted @ 2021-09-29 19:32  举个栗子走天下  阅读(372)  评论(0编辑  收藏  举报