简体   繁体   中英

split string using parameter error?

Using just the parameter fails but using a variable works, what is the difference?

<script type="text/javascript">
    function Person(name) {
        //Throws error - name.reverse is not a function
        name.split("");
        name.reverse();
        name.join("");

        // Works
        var splitString = name.split("");
        var reverseString = splitString.reverse();
        var joinString = reverseString.join("");
        return joinString;
    }
    document.write(Person("Joe"));
</script>

A string cannot be reversed using name.reverse(). reverse() is a method of array. this is the solution

function Person(name) {
    //Throws error - name.reverse is not a function
    name = name.split("");
    name = name.reverse();
    name = name.join("");
    return name;
}

From MDN documentation of split :

Return value

An array of strings split at each point where the separator occurs in the given string.

It returns an array, does not change the type of variable in-place... Actually, no operation I know of changes the type of variable in-place.

return name.split("").reverse().join("");

The point is what happens to name in the first three function calls. The answer is absolutely nothing .

name.split("");
name.reverse();
name.join("");

This says "split name , then discard the result, then reverse it and discard the result, then join it and discard the result". name never ceases to be the original string. And, crucially, reverse and join are not string functions but array functions.

Now let's look at the other calls.

var splitString = name.split("");
var reverseString = splitString.reverse();
var joinString = reverseString.join("");
return joinString;

Here you are actually using the results of the function calls. You are saying "split the name into an array of characters and call this array splitString , then reverse the array of characters and call it reverseString , then join that array together and call it joinString , then return joinString .

Note that splitString and reverseString are, technically, not strings. They are arrays, which is why join and reverse work.

The other option, of course, is to chain it:

return name.split("").reverse().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