This article mainly shares with you the method of inverting strings in javascript. I hope it can help you.
Javascript method of inverting a string
Method 1:
var str = "abcdefg"; //常规方法使用for循环加charAt function reverse(str){ var result =""; for(var i = str.length; i > 0; i-- ){ console.log(str.charAt(i-1)); result += str.charAt(i-1); } return result; }
Output result:
Method 2: Cleverly use the reverse and join methods of array
//巧妙使用array的reverse和join方法 function reverse(str){ var result, arr = str.split(""); //使用空字符则会直接分割字符返回数组[a,b,c,d,e,f,g] var result = arr.reverse().join(""); return result; }
Output results:
Sometimes during the project When you encounter some better methods, it is good to record them. For example, if the js native domList wants to use the array method, you can also do this, so that you can avoid excessive use of for loops
var op = document.querySelectorAll("select option"); var arr = Array.prototype.slice.call(op,1); arr.forEach(function(item, index, arr){ item.style.backgroundColor = "red"; console.log(index); console.log(item); console.log(arr); });
Related recommendations:
Summary of JavaScript string methods
The above is the detailed content of How to implement inverted string in javascript. For more information, please follow other related articles on the PHP Chinese website!