这个javascript的结果是什么?

时间:2017-11-18 21:14:31

标签: javascript

function getAttackString() { 
    var foo = "d322yvb34"; 
    var bar = "x3nj4nhj9";
return "The code is: "+(foo.substr(3,foo.length-6))+(bar.substr(2);
    }

我不知道“+(foo.substr(3,foo.length-6))+(bar.substr(2)”的含义是什么。

3 个答案:

答案 0 :(得分:1)

从字符串索引3开始,从foo.length-6获取foo个字符(3)的子字符串:

foo.substr(3,foo.length-6)

这将从字符串索引bar开始获取2中所有字符的子字符串:

bar.substr(2)

然后连接起来。

您发布的代码有一个小错字。这是工作代码。

function getAttackString() {
  var foo = "d322yvb34";
  var bar = "x3nj4nhj9";
  return "The code is: " + (foo.substr(3, foo.length - 6)) + bar.substr(2);
}

console.log(getAttackString())

答案 1 :(得分:0)

您可以查看String#substr

的参数
str.substr(start[, length])

考虑到这一点,您可以完成所有部分并通过单个部分进行手动操作:

indices  012345678               action
string   d322yvb34   
                                 foo.substr(3, foo.length - 6)
            2yv                  foo.substr(3, 9 - 6) 

indices             012345678
string              x3nj4nhj9
                      nj4nhj9    bar.substr(2)

result      2yv       nj4nhj9

获得结果

2yvnj4nhj9

答案 2 :(得分:0)

以下是您的完整代码说明。

// getAttackString is a function and the function name is "getAttackString"
     function getAttackString() {
          var foo = "d322yvb34";
          var bar = "x3nj4nhj9";

          //The substr() method extracts parts of a string, beginning at the character 
          //at the specified position, and returns the specified number of characters.

          return "The code is: " + (foo.substr(3, foo.length - 6)) + bar.substr(2);

          //Lets see what is going on here...
          //       012345678
          //foo = "d322yvb34"
          //(foo.substr(3, foo.length - 6)) + bar.substr(2);
          //Start from 3rd char (this means start at "2yvb34"), 
          //End at (foo.length - 6) i.e 9-6 = 3 = "2yv" 
          //Add bar.substr(2) bar = x3nj4nhj9
          //Start from 2 i.e = "nj4nhj9"
          //Now add "2yv" + "nj4nhj9" = "2yvnj4nhj9"

        }
        console.log(getAttackString())