排序对象javascript
Sort object javascript
有很多类似的问题,但我找不到任何像这样的。这是我的代码。
for (var i = 0; i < count_batters; i++) {
var post = {
player_name: jsonData[i].player_name,
fantasy_points: jsonData[i].avg_fpts_fd
}
console.log(post);
function compare(a,b) {
if (a.fantasy_points < b.fantasy_points)
return -1;
if (a.fantasy_points > b.fantasy_points)
return 1;
return 0;
}
post.sort(compare);
我想按"fantasy_points"对"post"进行排序。默认情况下按player_name排序。我已经尝试过。sort(),它在这个对象上不起作用。上面代码给出的错误是undefined is not a function
将对象放入数组中,然后可以对数组进行排序:
var posts = [];
for (var i = 0; i < count_batters; i++) {
var post = {
player_name: jsonData[i].player_name,
fantasy_points: jsonData[i].avg_fpts_fd
};
posts.push(post);
}
function compare(a,b) {
if (a.fantasy_points < b.fantasy_points)
return -1;
if (a.fantasy_points > b.fantasy_points)
return 1;
return 0;
}
posts.sort(compare);
看起来你的比较函数是for循环内部?如果你把它拿出来,我想它会起作用的。或者你可以把一个匿名函数放到sort中作为比较函数
post.sort(function(a,b) {
if (a.fantasy_points < b.fantasy_points)
return -1;
if (a.fantasy_points > b.fantasy_points)
return 1;
return 0;
}
相关文章:
- Chrome开发工具(如何知道我在调用哪个javascript对象)
- 循环遍历以数组为值的Javascript对象
- 从ajax请求中获取javascript对象
- 如何从对象的原型方法访问JavaScript对象属性
- 将XML转换为普通的旧JavaScript对象
- 通过引用传递JavaScript对象
- javascript对象操作:根据指定条件选择属性
- Javascript对象类在单击时打开窗口进行颜色选择,并在更改时替换对象背景颜色
- 如何在异步函数中使用javascript对象
- 临时Javascript对象
- 如何在ASP中为用户控件添加Javascript对象网
- 使用数组向下搜索Javascript对象
- Rails将JavaScript对象存储到Model的有效方式
- JavaScript对象不是从原型链继承的
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- SetInterval在javascript对象中表现怪异
- Javascript 对象和 this 关键字
- 如何在不知道关键字的情况下访问javascript对象值
- 在 JavaScript 对象中设置要使用的运算符的属性
- 如何搜索JavaScript对象并更改值