【问题标题】:Arrays undefined vs -1数组未定义 vs -1
【发布时间】:2017-11-21 05:25:31
【问题描述】:

为什么说这段代码这两个输出有区别:

var animals = ["a", "b", "c", "d"];

console.log = [4];
console.log(animals.indexOf("e"));

同理,为什么它在 indexOf 处显示 undefined vs -1?

【问题讨论】:

  • 在console.log = [4]中,您将控制台对象的日志键分配给数组[4](默认情况下,console.log被分配了一个记录到控制台的函数)
  • animals 是一个错字。正确的应该是animal
  • 你使用了两个不同的数组 animal 和 animals
  • 你想用console.log = [4]做什么?你的意思是console.log([4])

标签: javascript arrays console.log


【解决方案1】:

indexOf() 在数组中查找“e”。如果找到它会返回它所在的位置,否则它总是返回-1。

console.log = [4] 将 [4] 分配给 console.log,它会覆盖函数 console.log() 并为其分配一个值为 4 的数组的值。

【讨论】:

    【解决方案2】:

    应该这样写(所有错误都已更正):

    var animal = ["a", "b", "c", "d"];
    console.log(animal.indexOf("e"));
    

    现在可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-06
      • 2022-08-23
      • 1970-01-01
      • 2022-11-10
      • 2012-01-07
      • 1970-01-01
      • 2017-10-29
      • 2015-12-01
      相关资源
      最近更新 更多