【问题标题】:javascript typeof index in the iteration? [duplicate]迭代中的javascript typeof索引? [复制]
【发布时间】:2020-08-02 05:33:22
【问题描述】:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const index in digits) {
  console.log(typeof digits[index]);
  console.log(digits[index]);
}


console.log('========================')

const digitsz = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
for (const indexz in digitsz) {
  console.log(typeof indexz);
  console.log(indexz);
}

现在第一个类型的返回是数字,而第二个是字符串 我不知道这是为什么?而在数组中,它已经有数字了

【问题讨论】:

  • 尝试使用布尔数组或对象数组。这应该表明只有第一个 typeof 测试数组中的值。
  • 这里使用两个单独的数组是完全的红鲱鱼。区别在于您检查的是什么类型,与数组之间的区别无关。
  • 在 Javascript 中,一切都是对象。甚至数组。在第二个循环中,您正在记录 indexz,它是数组对象中的一个键,因此它的类型为 string

标签: javascript arrays


【解决方案1】:

'for...in 循环仅迭代可枚举的非符号属性。从 Array 和 Object 等内置构造函数创建的对象从 Object.prototype 和 String.prototype 继承了不可枚举的属性,例如 String 的 indexOf() 方法或 Object 的 toString() 方法。循环将遍历对象本身的所有可枚举属性以及对象从其构造函数的原型继承的那些属性(原型链中更接近对象的属性覆盖原型的属性)。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

【讨论】:

  • 非常感谢你已经解释了很多对不起无聊的问题
猜你喜欢
  • 2022-01-11
  • 2016-06-05
  • 2013-11-17
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 2016-07-15
相关资源
最近更新 更多