【问题标题】:Subtracting from the length of an array从数组的长度中减去
【发布时间】:2017-11-25 03:51:49
【问题描述】:

需要澄清以下内容。答案是“狗”,想知道为什么。

例子:

var animals = ["parrot", "cat", "dog"];

console.log(animals[animals.length - 1]);

控制台 = “狗”。

【问题讨论】:

  • javascript 中的数组是 0 索引的。所以最后一个元素位于索引length - 1,因为第一个元素位于1 - 1i-th 元素的索引为 i - 1
  • 数组长度为3,索引为0、1、2。

标签: javascript string-length


【解决方案1】:

动物长度 = 3 包含 3 个元素。
Animals.length - 1 = 第二个元素(3-1)。瑞特?

如果您在 Animal 中看到索引 2,则该值为 dog,因为数组从 0 索引开始。

 Animal[0] = parrot
 Animal[1]=cat 
 Animal[2]=dog

【讨论】:

    【解决方案2】:

    array[index] 是一种访问数组元素的方法。在您的情况下,animals 在数组中,animal.length-1 将是一个数字。index 从 0 开始,因此 animal.length-1 将指向索引为2的元素。在这个数组中dog占据了第二个索引,所以是安慰狗

    var animals = ["parrot", "cat", "dog"];
    console.log(animals.length) // 3
    var _index = animals.length - 1 // 2
    console.log(animals[_index]) // will print element in the index 2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 2015-06-24
      相关资源
      最近更新 更多