【问题标题】:"sort not a function" error in angularjs only in google chromeangularjs中的“排序不是函数”错误仅在谷歌浏览器中
【发布时间】:2015-09-05 00:52:49
【问题描述】:

我遇到了这个问题,无法弄清楚原因,也无法在谷歌上找到任何解释。我有一个 $http.get 方法可以从 url 中检索一些数据,成功后我正在对响应进行排序。但是当我在谷歌浏览器上运行页面时,我收到错误“TypeError:response.sort is not a function”

var orderOfGroups = ["alpha", "beta", "gamma", "delta"];

$http.get(url)
.success( function (response, status, headers, config) {
    response.sort( function(a, b) {
        var aname = orderOfGroups.indexOf(a.team);
        var bname = orderOfGroups.indexOf(b.team);

        return bname-aname;
    });
});

我在“response.sort”行收到错误消息。这也只发生在 google chrome 中,我在 firefox 和 IE10 中对其进行了测试,并且在这些浏览器上运行良好。 我收到(响应)的json数据格式如下

[
    {
        team: "gamma",
        value: "p"
    },
    {
        team: "alpha",
        value: "q"
    },
    ......
]

您能告诉我如何解决这个问题吗?

【问题讨论】:

  • response array?如果不使用response = JSON.parse(response);
  • response总是array吗?
  • 是的,响应总是一个对象数组。对象类型也不会改变。
  • console.log(response instanceof Array) 是什么?
  • 它在 chrome 中打印“false”,在其他浏览器中打印“true”。 “GET /TYPE=GETLIST HTTP/1.1”被添加到数组的开头,整个数组被转换成chrome中的文本。知道为什么会这样吗?

标签: javascript angularjs google-chrome sorting


【解决方案1】:

您的response 不是数组。它可能是一个对象,其属性包含数组(例如response.data)或数组的字符串版本,然后您需要使用JSON.parse 并将字符串转换为数组。

无论如何,sort 在 Array 的原型上 - 这意味着所有数组都将具有该属性 - 这与 AngularJSgoogle chrome 无关。

【讨论】:

  • $http.get 如何与 AngularJS 无关。
  • "TypeError: response.sort is not a function" - 这不相关。 $http.get 不会根据您的浏览器返回不同的值。
  • 当然,该特定错误不是来自 Angular。但是,我们必须从所有与使用库时发生的错误有关的问题中去掉库标签。
  • @akashrajkn - 添加一个 console.log(response);和 console.log(response instanceof Array) 并粘贴结果。
  • 由于此数据出现在响应中,我很确定服务器会返回它。运行嗅探器并检查服务器的确切响应(在所有浏览器中)并检查天气是服务器问题还是谷歌浏览器。
猜你喜欢
  • 2019-12-14
  • 2017-08-01
  • 2012-10-16
  • 2021-11-08
  • 2014-09-16
  • 1970-01-01
  • 2022-10-31
  • 1970-01-01
  • 2012-03-06
相关资源
最近更新 更多