我需要知道的是一种index在sort方法的比较函数中获取当前信息的方法array.假设这段代码:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function (a, b) {
return a - b;
//i need the current index of `a` and `b` here
});
Run Code Online (Sandbox Code Playgroud)
在匿名函数中,我需要当前索引a和b对象.我怎么才能得到它?
使用索引创建一个对象数组...
var arr = [1,5,2,3,8,13, 1];
var arr2 = arr.map(function(o, i) {return {idx: i, obj: o}; }).sort(function(a, b) {
console.log('a.idx:', a.idx, 'b.idx:', b.idx);
return a.obj - b.obj;
});
for(var i = 0, j = arr2.length; i < j; i++){
console.log('i:', i, 'arr2[i].obj:', arr2[i].obj);
}
Run Code Online (Sandbox Code Playgroud)
小提琴:https://jsfiddle.net/k6xdqpb2/
a或的索引b?
var indexOfA = points.indexOf(a);
Run Code Online (Sandbox Code Playgroud)
这将为您提供第一个索引a 出现在数组中的
根据您想要执行的操作,另一种选择可能是使用 进行排序,如“使用地图排序”标题下map的更多详细信息所述。deostroll 的回答中给出了这种方法的示例。