[英]javascript indexOf strange behavior
I found a strange unexplainable behavior while writing a piece of test code for my javascript program. 在为我的javascript程序编写一段测试代码时,我发现了一个奇怪的无法解释的行为。 I was comparing an output of res.body to check if it contains a string.
我正在比较res.body的输出以检查它是否包含字符串。
More precisely, I was checking if res.body contained a string 'channel'. 更准确地说,我正在检查res.body是否包含字符串'channel'。
Even though the output did really contain that string, the test case was always failing. 即使输出确实包含该字符串,测试用例也总是失败。 I ran the program in debug mode, to examine why it is failing.
我以调试模式运行该程序,以检查其失败原因。 The results are puzzling, to say the least.
至少可以说,结果令人困惑。
> res.body
'Error: invalid channnel'
> res.body.indexOf('channel')
-1
> res.body.indexOf('channe')
-1
> res.body.indexOf('chann')
15
>
if I try to check indexOf of 'channel' in res.body whose value was 'Error: invalid channel', I was supposed to get a positive value, but it gives -1. 如果我尝试在值是“错误:无效通道”的res.body中检查“通道”的indexOf,我应该得到一个正值,但它给出-1。
so, I tried by reducing the no. 因此,我尝试通过减少No。 of chars in the match, it still fails until I reduce the search string to contain just 'chann' ie by omitting 'el'.
匹配中的字符数,直到我将搜索字符串减少为仅包含“ chann”(即省略“ el”)后,它仍然失败。
But this behavior doesn't happen, if I take a string litteral and do the same exercise. 但是,如果我乱扔垃圾并进行相同的练习,则不会发生这种情况。 For example, the below works perfectly.
例如,下面的方法可以正常工作。
> 'Error: invalid channel'.indexOf('channel')
15
I went ahead and checked the typeof res.body, and it shows as string, and not any object. 我继续检查了res.body的类型,它显示为字符串,而不是任何对象。
> typeof res.body
'string'
>
Did anyone face a similar problem ever? 有人遇到过类似的问题吗? Or is there an explanation to this?
还是对此有一个解释?
EDIT It happens when I res.body as produced by mocha + chai framework. 编辑当我重新尝试由mocha + chai框架生成的body时,就会发生这种情况。 The full code is below:
完整的代码如下:
58 it ("Should fail with 400, if invalid channel", function(done) {
59 chai.request(app).post('/campaigns/js')
60 .send(samples.type0.invalidChannel)
61 .end(function(err, res) {
62 console.log("response:", res.body);
63 expect(res).to.have.status(400);
>64 debugger;
65 expect(res.body).to.contain('channel');
66 return done();
67 });
68 });
You're res.body
has channel
with 3 n
s. 您的
res.body
拥有3 n
s的channel
。
'Error: invalid channnel'
“错误:频道无效”
This means that chann
matches, but channe
won't because of the extra n
. 这意味着
chann
匹配,但是channe
不会因为额外的n
。
In the first piece of code, "channnel" has 3 n's. 在第一段代码中,“通道”具有3 n。 That's why it matched "chann" but not "channe".
这就是为什么它匹配“ chann”而不匹配“ channe”的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.