简体   繁体   English

使用参数分割字符串错误?

[英]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(). 不能使用name.reverse()来反转字符串。 reverse() is a method of array. reverse()是数组的方法。 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 : 从MDN 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. 问题的关键是发生了什么name的前三个函数调用。 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 ,然后丢弃结果,然后反转并丢弃结果,然后加入并丢弃结果”。 name never ceases to be the original string. name永远不会停止是原始字符串。 And, crucially, reverse and join are not string functions but array functions. 而且,至关重要的是, reversejoin不是字符串函数,而是数组函数。

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 . 您说的是“将name拆分为一个字符数组,并将其称为splitString数组,然后反转字符数组并将其称为reverseString ,然后将该数组连接在一起并称为joinString ,然后返回joinString

Note that splitString and reverseString are, technically, not strings. 请注意, splitString技术上讲, splitStringreverseString不是字符串。 They are arrays, which is why join and reverse work. 它们是数组,这就是joinreverse工作的原因。

The other option, of course, is to chain it: 当然,另一个选择是将其链接:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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