- 我正在尝试学习 js 基础知识。
- 我尝试分析字符串计数代码,但我不确定某些语句。
- 你们能告诉我为什么它以这种方式行事吗?
- 这将有助于更好地理解,将来,我可以自己解决问题。
- 在下面提供代码
String.prototype.count=function(c) {
var result = 0;
var i = 0;
console.log("this--->" + this); // how come this prints strings here, since we dont pass stings here
console.log("this.length--->" + this.length);
for(i;i<this.length;i++)
{
console.log("this[i]--->" + this[i]); // here we did not declare this an array anywhere right then how come its taking this[i] as s and stings also we did not put in any array
console.log("c--->" + c);
if(this[i]==c)
{
result++;
console.log("inside if result++ ---->" + result++);
// here it prints 1 and 3 but only two times s is present so it should print 1 and 2 right
}
}
console.log("out of for loop result--->" + result);
// how its printing 4 but s is present only two times
return result;
//console.log("out of for loop result--->" + result);
};
console.log("strings".count("s")); //2
output
this--->strings
this.length--->7
this[i]--->s
c--->s
inside if result++ ---->1
this[i]--->t
c--->s
this[i]--->r
c--->s
this[i]--->i
c--->s
this[i]--->n
c--->s
this[i]--->g
c--->s
this[i]--->s
c--->s
inside if result++ ---->3
out of for loop result--->4
4
代码示例中的问题基本上是关于 2 个问题:
-
这 - 是 JS 关键字。您不必初始化它,它每次都会自动定义,在您的 JS 代码中的任何地方。在不同的情况下,它可能意味着不同的东西,但如果你刚刚开始学习JS,这是一个太高级的话题。现在让我们说,
this
指的是上下文,称为count()
函数,即字符串"strings"
。所以它有长度,你可以把它作为一个字符数组进行迭代 - 为什么计数上升到第 4 位,而它应该是 2 位?因为当您发现字符串的当前字母与字符
"s"
(带有this[i]==c
的行(匹配时,您使用result++
将结果递增 1。但是你也会在它之后立即在你的console.log
中这样做,所以每次找到匹配项时它都会增加 2
console.log("this--->" + this); // how come this prints strings here, since we dont pass stings here
这会打印一个字符串,因为您有一个字符串 + 某些东西。 这称为字符串串联,字符串串联的结果是字符串。 在这种情况下,this
是调用 count 函数的对象,该函数是一个字符串。
console.log("this[i]--->" + this[i]); // here we did not declare this an array anywhere right then how come its taking this[i] as s and stings also we did not put in any array
this
是一个字符串。 字符串上的括号表示法将返回提供的索引处的字符。
result++;
console.log("inside if result++ ---->" + result++);
// here it prints 1 and 3 but only two times s is present so it should print 1 and 2 right
result++
表示法与result += 1
相同,但result++
在计算值后添加 1 U,而++result
之前会这样做。 因此,在此示例中,事件的顺序为:将结果加 1,然后打印console.log
,然后在结果中添加 1
希望对您有所帮助!