gpt4 book ai didi

javascript - 在排序函数中获取当前索引

转载 作者:行者123 更新时间:2023-12-04 22:59:31 27 4
gpt4 key购买 nike

我需要知道的是获取当前 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
});

在匿名函数中,我需要 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);
}

fiddle : https://jsfiddle.net/k6xdqpb2/

关于javascript - 在排序函数中获取当前索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30167117/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com