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