簡體   English   中英

如何在JavaScript中對數組進行排序?

[英]How do I sort an array in JavaScript?

在數組T中,我們有值[b,a,d,c] 如何在單個循環中重新排序此數組以獲得[a,b,c,d]

你可以使用.sort()方法,如:

var T = new Array('a', 'd', 'c', 'b');
T.sort();

我真的不明白“重新排序”是什么意思(也許按照一些隨機順序排序:)

但是,你可以隨時使用for ,例如:

// create new array
var U = new Array();
for (i=0; i<T.length; i++) {

    // some desired condition
    if (T[i] <= 1) {
        // put the value ( T[i] ) on the desired position
        desired_position = ???
        U[desired_position] = T[i];
    }
    else {
        // otherwise put it at the end of the array
        U.push(T[i]);
    }
}

// and here you have the "reordered" array 
alert('the array U is reordered !!');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM