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 @ 2018-07-22 16:37  清风晰心  阅读(32748)  评论(0编辑  收藏  举报