data.map不是函数 [英] data.map is not a function

查看:322
本文介绍了data.map不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为无法解决的错误ash之以鼻.我有以下内容;

I'm bashing my head against an error I cant work out how to fix. I have the following;

JSON

{"products":
[
    {
        "product_id" : "123",
        "product_data" : {
            "image_id" : "1234",
            "text" : "foo",
            "link" : "bar",
            "image_url" : "baz"
        }
    },{
        "product_id" : "456",
        "product_data" : {
            "image_id" : "1234",
            "text" : "foo",
            "link" : "bar",
            "image_url" : "baz"
        }
    }
]}

和以下jQuery

function getData(data) {
    this.productID = data.product_id;
    this.productData = data.product_data;
    this.imageID = data.product_data.image_id;
    this.text = data.product_data.text;
    this.link = data.product_data.link;
    this.imageUrl = data.product_data.image_url;
}

$.getJSON("json/products.json").done(function (data) {

    var allProducts = data.map(function (item) {
        return new getData(item);
    });
});

但是我收到一个错误,指出map.data未定义为函数?看着它,我不知道什么不起作用,因为我已将其从以前使用的代码复制到新项目中.唯一不同的是json源.前一个在{]括号之前没有{"products":部分.这是什么让我失望吗?

yet i'm getting an error that map.data is undefined as a function? Looking at it I don't know whats not working as I've copied this to a new project from previously used code. The only thing different is the json source. The previous one didnt have the {"products": part before the [] brackets. Is this whats throwing me off?

推荐答案

JavaScript中的对象{}没有方法.map(),仅用于

Objects, {}, in JavaScript does not have the method .map(), it's only for Arrays, [].

因此,为了使代码正常工作,将data.map()更改为data.products.map(),因为products是可以迭代的数组.

So in order for your code to work change data.map() to data.products.map() since products is an array which you can iterate upon.

这篇关于data.map不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆