Home > Web Front-end > JS Tutorial > How to implement inverted string in javascript

How to implement inverted string in javascript

小云云
Release: 2018-03-15 16:40:59
Original
2818 people have browsed it

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;
                }
Copy after login

Output result:

How to implement inverted string in javascript

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;  
                }
Copy after login

Output results:

How to implement inverted string in javascript

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); 
                });
Copy after login

​​​

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template