【问题标题】:Cannot loop the Array-like Object [duplicate]无法循环类似数组的对象[重复]
【发布时间】:2019-09-18 16:43:48
【问题描述】:

我有一个从服务器接收到的对象产品数组。

return response()->json(['products' => $products->toArray()]);

这是它的日志:

而且我需要遍历它来获得product.attributes,我认为它是一个类似数组的对象,所以我使用Array.prototype.forEach.call

                this.products.forEach(product => {
                    console.log(product);
                    console.log(product.attributes);

                    Array.prototype.forEach.call(product.attributes, function(child) {
                        // It seems the loop doesn't work, so nothing is printed out.
                        console.log(child);
                    });
                });

但类似数组的对象上的循环似乎不起作用,因此没有打印任何内容,即使我的product.attributes 也不是空的。这是product.attributes日志:

【问题讨论】:

  • -> 表示法是什么?看起来不像 javascript?
  • 来自 Laravel
  • Object.keys [MDN, spec] — 一个函数,提供一个对象自身的名称数组,其名称是字符串的可枚举属性。 Object.values [MDN, spec] — 提供对象自身的可枚举属性值数组的函数。

标签: javascript vue.js


【解决方案1】:

products.attributes 不是像对象那样的数组,它是对象。

但如果你愿意,你仍然可以迭代到那个。你只需要:

Object.entries(product.attribues).forEach(([key, value]) => {  })

【讨论】:

    【解决方案2】:

    您的product.attributes 也是一个对象。所以Array.prototype.forEach.call 不起作用。

    试试for...in statement

    for (var key in product.attributes) {
      console.log(product.attributes[key]);
    }
    

    【讨论】:

    • 不要把网址作为答案,因为网站包含的内容将来可能会发生变化,所以尝试通过阅读网站来回答并提及该网站作为参考。
    • @Lakmi 感谢您提醒我。编辑了我的答案
    猜你喜欢
    • 2020-10-31
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2019-02-22
    • 2021-12-15
    • 2023-04-05
    相关资源
    最近更新 更多