日期:2014-05-16 浏览次数:20473 次
var arr = new Array(40,20,30); function sortByNumber(a, b) { return b.v - a.v; } function mySort(ar) { var ar_tmp = [], result = []; for (x in ar) ar_tmp.push({k: parseInt(x) + 1, v: ar[x]}); ar_tmp.sort(sortByNumber); for (i in ar_tmp) result.push(ar_tmp[i].k); return result; } alert(mySort(arr)); //1,3,2
------解决方案--------------------
var arr = new Array(40,20,30); var a = []; var b = []; for(var i in arr) a.push({"idx":i, "val":arr[i]}); a.sort(function(x, y){ return y.val - x.val; }); for(var i in a) a[i].pos = parseInt(i,10)+1; a.sort(function(x, y){ return x.idx - y.idx; }) for(var i in a) b.push(a[i].pos); alert(b.join(","))
------解决方案--------------------
<!DOCTYPE HTML> <html> <head> <meta charset="gb2312" /> <title></title> </head> <body> <script> Array.prototype.clone = function(){ var tmp = []; for(var i = 0, len = this.length; i < len; i++){ tmp.push(this[i]); } return tmp; } Array.prototype.find = function(val){ for(var i = 0, len = this.length; i < len; i++){ if( this[i] === val ){ return i; } } return -1; } var arr = [40, 20, 30, 15, 8, 76]; var tmp = arr.clone().sort(function(a, b){return b - a;}) var re = []; for(var i = 0, len = arr.length; i < len; i++){ re.push(tmp.find(arr[i])+1); } alert(re); </script> </body> </html>
------解决方案--------------------
> var arr = [40, 20, 30]; undefined > var result = [1,2,3]; undefined > result.sort(function(a, b) { return arr[b-1]-arr[a-1];}); [ 1, 3, 2 ]