【问题标题】:What are the differences between substr method and slice method in this exercise?本练习中的 substr 方法和 slice 方法有什么区别?
【发布时间】:2017-10-01 21:14:49
【问题描述】:

我目前正在为自己进行方法练习,并遇到了两个不同的方法,它们的功能有点相似。然而,即使两者的第一个参数是字符串的起始索引,第二个参数也会让我感到困惑和困惑。

这是我所说的一个例子。

var newStringMethod = 'lets try a subslice method on this string primitive data type variable';

这是我在本练习中为自己创建的字符串变量。

我从这个变量的 substr 方法开始......

var subSlice = newStringMethod.substr(7, 10);

调用 subSlice 后,这作为我的值返回。

"y a subsli"

我继续使用切片方法。

var reguarSlice = newStringMethod.slice(7, 10);

一旦我调用它,我就会返回这个值。

"y a"

为了理解整个事情,我所做的只是简单地计算每个单独的字母,从 0 开始。仅仅使用它来理解它们就清楚地表明我需要对这两种方法进行进一步的解释。这两个字符串方法的第二个参数分别有哪些可区分的属性和功能?

【问题讨论】:

    标签: javascript string methods


    【解决方案1】:

    您必须注意.slice(7, 10) 方法将返回从7 索引到10 索引的字母(不包括10th 索引上的字母)。

    var newStringMethod = 'lets try a subslice method on this string primitive data type variable';
    console.log(newStringMethod.slice(7, 10));

    .substr(7, 10) 方法将返回 10 个字母,从 7 索引开始。

    var newStringMethod = 'lets try a subslice method on this string primitive data type variable';
    console.log(newStringMethod.substr(7, 10));

    如果您正在寻找相同的结果,请改用.substring 函数,它将返回与slice 相同的结果。

    var newStringMethod = 'lets try a subslice method on this string primitive data type variable';
    console.log(newStringMethod.substring(7, 10));

    【讨论】:

      【解决方案2】:

      这两种方法的可区分属性是:

      substr 将从字符串中的第 7 个字符开始输出接下来的 10 个字符。这是一个更直观的例子:

      '让 tr(y)<- 7th index 在这个字符串原始数据类型变量上使用 subsl(i)<-10th index from 7thce 方法'

      slice 将简单地将第 7 个字符输出到第 10 个 (7 - 10) 个字符,包括空格。这是切片正在做什么的更直观的示例。

      让 tr(y a)<- 7th to 10th index 在这个字符串原始数据类型变量上使用 subslice 方法

      【讨论】:

        【解决方案3】:

        String#substr 语法:

        str.substr(startIndex, length)
        

        substr() 方法从以startIndex 开始的字符串返回指定数量的字符(length)。

        例如:

        var newStringMethod = 'lets try a subslice method on this string primitive data type variable';
        //                            ----------
        //                            start at index 7 and return 10 characters
        var subSlice = newStringMethod.substr(7, 10);
        // returns "y a subsli"
        

        String#slice 语法:

        str.slice(beginIndex[, endIndex])
        

        slice() 方法从beginIndexendIndex 中提取一段字符串。如果未指定endIndex,则它将从beginIndex 中提取字符串部分到字符串末尾。另请注意,endIndex 处的字符不会包含在结果中。

        例如:

        var newStringMethod = 'lets try a subslice method on this string primitive data type variable';
        //                            ---
        //                            start at index 7 and ends at index 10 excluding value at endIndex 10
        var reguarSlice = newStringMethod.slice(7, 10);
        // returns "y a"
        

        【讨论】:

          猜你喜欢
          • 2011-05-31
          • 1970-01-01
          • 2013-09-20
          • 2019-11-04
          • 2013-04-29
          • 2017-07-19
          • 1970-01-01
          • 1970-01-01
          • 2010-11-06
          相关资源
          最近更新 更多