简体   繁体   中英

When .unshift-ing an array to a string, how do I avoid having the “,” between each character?

I am working on the project of reversing a string and am getting commas in between each character in the reversed string.

`var testString = prompt("Enter a 'string'");

document.getElementById("demo").innerHTML = testString;

var reverse = function(string){
    var gnirts = [];
    for (i = 0; i < string.length; i++){
        gnirts.unshift(string[i]);
    };
    gnirts.toString();
    document.getElementById("revString").innerHTML = gnirts;
};

reverse(testString);`

I entered "Honky Toast" in the prompt and "t,s,a,o,T, ,y,k,n,o,H" was returned. Why am I getting the ","s and how do I avoid them?

Use join, and pass an empty string as separator.

REPL:

x = [1,2,3,4,5]
[ 1, 2, 3, 4, 5 ]

x.join()
'1,2,3,4,5'

x.join('')
'12345'

Instead of calling gnirts.toString(); You should use join . Array's implementation of toString separates each item with a comma.

var reverse = function(string){
    var gnirts = [];
    for (i = 0; i < string.length; i++){
        gnirts.unshift(string[i]);
    };
    document.getElementById("revString").innerHTML = gnirts.join('');
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM