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
答案 0 :(得分:0)
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,++result
之前会执行此操作。所以在这个例子中,事件的顺序是:
将1添加到结果中,然后打印console.log
,然后将1添加到结果
希望有所帮助!
答案 1 :(得分:0)
您的代码示例中的问题基本上是关于2个问题:
this
指的是上下文,称为count()
函数,即字符串"strings"
。所以它有长度,你可以作为一个字符数组迭代它"s"
(带有this[i]==c
的行)之间找到匹配项时,您使用result++
将结果增加1。但你也可以在console.log
之后立即执行此操作,因此每次找到匹配时它会增加2