我在循环中排序对象时遇到问题。当我执行此代码时,我得到一个未捕获的TypeError:对象#没有方法'排序'。为什么?)我搜索了这个,但没有找到决心
for (var i = 0; i < responseData.Airlines.length; i++) {
function sortPrice() {
for (var s = 0; s < responseData.Airlines[i].FaresFull.length; s++) {
responseData.Airlines[i].FaresFull[s].Pricing.ADTTotal = parseFloat(responseData.Airlines[i].FaresFull[s].Pricing.ADTTotal);
responseData.Airlines[i].FaresFull[s].sort(function (a, b) {
return parseFloat(a.Pricing.ADTTotal) > parseFloat(b.Pricing.ADTTotal);
});
}
}
sortPrice();
}
答案 0 :(得分:2)
排序方法仅适用于Array对象。我想你正试图对一个纯粹的对象进行排序。
看:http://www.w3schools.com/jsref/jsref_sort.asp这里他们排序一个数组
答案 1 :(得分:0)
Sort是数组上的函数。您正在尝试对对象进行排序。试试这个:
function sortPrice() {
for (var i = 0; i < responseData.Airlines.length; i++) {
for (var s = 0; s < responseData.Airlines[i].FaresFull.length; s++) {
responseData.Airlines[i].FaresFull[s].Pricing.ADTTotal =
parseFloat(responseData.Airlines[i].FaresFull[s].Pricing.ADTTotal);
}
responseData.Airlines[i].FaresFull.sort(function (a, b) {
return parseFloat(a.Pricing.ADTTotal) - parseFloat(b.Pricing.ADTTotal);
});
}
}
您试图在每个元素上调用sort,而不是整个列表排序。我将内部for循环拉出来,并将比较器切换到-1,0,1。
答案 2 :(得分:0)
既然你没有告诉我们你想做什么或者你的数据看起来如何,我猜错了:
// move function header to top
function sortPrice(responseData) {
for (var i = 0; i < responseData.Airlines.length; i++) {
// dereference variables
var airline = responseData.Airlines[i];
for (var s = 0; s < airline.FaresFull.length; s++) {
var pricing = airline.FaresFull[s].Pricing;
pricing.ADTTotal = parseFloat(pricing.ADTTotal);
}
// move outside the loop
airline.FaresFull .sort(function (a, b) {
// ^ no [s] - sort the array
// don't do parseFloat another time
return a.Pricing.ADTTotal - b.Pricing.ADTTotal;
});
}
}
sortPrice(yourData);