小编New*_*his的帖子

为什么 indexOf 在按原样使用与将其与 -1 进行比较时工作不同?

似乎无法找到答案,可能是因为我缺乏谷歌搜索经验,而且 indexOf 的 mozilla 页面似乎没有回答

//this returns -1 because it can't find 'ca' within cat
var randomArr = ['dog', 'cat', 'bird', 'cheetah'];
console.log(randomArr.indexOf('ca'));

//this returns 1 which is correct, but why?
var randomArr = ['dog', 'cat', 'bird', 'cheetah'];
for (var i = 0; i < randomArr.length; i++) {
  if (randomArr[i].indexOf('ca') !== -1) {
    console.log(i);
  }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么在使用 indexOf 时这会有所不同。为什么在一种情况下需要精确的字符串匹配,而在另一种情况下不需要?

javascript indexof

3
推荐指数
1
解决办法
41
查看次数

此函数中 Array() 的上下文

  it("should know properties that are functions act like methods", function() {
    var meglomaniac = { 
      mastermind : "Brain", 
      henchman: "Pinky",
      battleCry: function(noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = meglomaniac.battleCry(4);
    expect('They are Pinky and the Brain Brain Brain Brain').toMatch(battleCry);
  });
Run Code Online (Sandbox Code Playgroud)

这段代码(第 7 行)中 Array 的定义是什么?我查了一下,它看起来像是一个 Array.of() 命令,它生成一个长度为 n 的空数组,在这种情况下为 5?那么为什么假设这是正确的假设,它最终只有 4 个大脑输入?或者这个 array() 是做什么的?

javascript arrays jasmine

3
推荐指数
1
解决办法
70
查看次数

标签 统计

javascript ×2

arrays ×1

indexof ×1

jasmine ×1