【问题标题】:replace for in with regular for loop with objects用带有对象的常规 for 循环替换 for in
【发布时间】:2017-03-13 00:08:07
【问题描述】:

出于好奇,我目前正在尝试用常规 for 循环替换我拥有的 for in 循环,但没有成功。我总是得到undefined。这甚至可以用 javascript 对象实现吗?

我循环的示例对象:

var el = {
    1: {type: "fish", commonName: "clownfish", scientificName: "sdasd", gender: "m", price: 1.99},
    2: {type: "fish", commonName: "dragonfish", scientificName: "dada", gender: "f", price: 2.99}
};

我的工作方法:

for (var element in el) {
   if (el[element].type === type && el.hasOwnProperty(element)) {
       elementNum++;
   }
}

总是让我着迷的简单 for 循环方法Cannot read property 'type' of undefined

for(var i = 0, x = Object.keys(el).length; i < x; i++) {
   if (el[i].type === type && el.hasOwnProperty(i)) {
      elementNum++;
   }
}

【问题讨论】:

  • @Matias 有正确的答案,但我想知道你为什么不使用数组?是否会跳过某些索引或其他内容?另外,切换(el[i].type === type &amp;&amp; el.hasOwnProperty(i)) 的顺序,这样如果el[i] 不存在,它就不会检查.type(因为如果发现一个错误的,javascript 会停止查看if AND 语句。

标签: javascript loops oop object for-loop


【解决方案1】:

您从0 开始循环,而整个对象中的第一个键是1

var el = {
  1: {
    type: "fish",
    commonName: "clownfish",
    scientificName: "sdasd",
    gender: "m",
    price: 1.99
  },
  2: {
    type: "fish",
    commonName: "dragonfish",
    scientificName: "dada",
    gender: "f",
    price: 2.99
  }
};

var keyLength = Object.keys(el).length;

// I've simplified the for loop
for (var i = 1; i <= keyLength; i++) {
  console.log(el[i].commonName);
}

【讨论】:

  • 答案不能再短了。不错!
  • 该死,我怎么看不到这个。。谢谢!!
  • @Sebsemillia 我会认为有时我的大脑就像一个语言提示工具(JSHint,JSLint...)lol
  • @MatíasFidemraizer 呵呵^^
  • 与原来的for (var element in el) { 方法相比,这种方法有什么好处吗?
【解决方案2】:

我建议直接遍历对象的键。

function getCount(type) {
    return Object.keys(el).reduce(function (r, k) {
        return r + +(el[k].type === type);
    }, 0);
}

var el = { 1: { type: "fish", commonName: "clownfish", scientificName: "sdasd", gender: "m", price: 1.99 }, 2: { type: "fish", commonName: "dragonfish", scientificName: "dada", gender: "f", price: 2.99 } };

console.log(getCount('fish'));

【讨论】:

  • 是的,我也知道这种方法。我只是想尝试用一个简单的 for 循环来做到这一点.. ;) 谢谢你的回答!
  • 它仅在对象采用固定的键表示法时才有效,例如索引。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 2022-01-14
  • 2011-09-22
  • 2016-11-18
  • 1970-01-01
  • 2019-04-04
相关资源
最近更新 更多