2014-12-23 73 views
0

如果我有10個元素(序列是很重要的)隨機使用jQuery

的陣列,並且我要插入在隨機點四個元件,插入在數組中的元素不搞亂現有數組的順序

什麼是最好的方法?

感謝和聖誕快樂

+0

請發佈您嘗試過的代碼。 – j08691

+0

看看[Array.splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) –

+1

我完全不明白。如果我有[A,B,C]這樣的列表,並且我隨機插入了'D',那麼所得到的[A,D,B,C]會不會混淆現有數組的順序? – alex

回答

4

使用splice()

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 
var b = [20, 21, 22, 23]; 

for (i = 0; i < 4; i++) { 
    var idx = Math.floor(Math.random() * a.length); 
    a.splice(idx, 0, b[i]); 
} 

console.log(a) 
// returns something like [23, 1, 2, 3, 22, 4, 5, 6, 7, 20, 8, 21, 9, 10] 

參考MDN Array.prototype.splice() docs

如果這不是預期的輸出認罪e提供樣品

0

試試這個:

var myArray = [1,2,3,4,5,6,7,8,9,0]; 

for(i=0; i<4; i++) { 
    var randomSpot = Math.floor(Math.random() * 10);  
    myArray[randomSpot] = i; 
}