溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JS中使用數(shù)組的示例分析

發(fā)布時間:2021-06-11 15:21:10 來源:億速云 閱讀:168 作者:小新 欄目:web開發(fā)

這篇文章將為大家詳細講解有關(guān)JS中使用數(shù)組的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

具體如下:

//數(shù)組的高級使用
 
var array = [10,12,20,30];
 
for(var index in array){
 console.log(array[index]);
}
 
//length 數(shù)組長度
 
for(var i = 0; i < array.length; i++){
 console.log(array[i]);
}
 
//數(shù)組添加新數(shù)據(jù)
 
array.push(1000);
 
array.push(2000);
 
array.push("hello world");
 
array.push({key:"jadeshu"});
 
console.log(array); //[10, 12, 20, 30, 1000, 2000, "hello world", {key:"jadeshu"}]
 
//數(shù)組刪除最后一個數(shù)據(jù)
 
array.pop();
 
console.log(array); // [10, 12, 20, 30, 1000, 2000, "hello world"]
 
//查找數(shù)組里面值的索引
 
var idex = array.indexOf(2000);
 
console.log(idex); //5
 
//數(shù)組刪除
 
//splice(開始索引,索引之后的個數(shù))
 
var data = array.splice(2,3);
 
console.log(data); //[20, 30, 1000]
 
console.log(array); //[10, 12, 2000, "hello world"]

1.給定一個數(shù)組,讓元素按照從大到小,從小到大排序

var array_num = [12,12,13,564,7,55,66];
 
//從小到大排序
 
array_num.sort(function (lhs,rhs) {
 
 if (lhs < rhs){
  return -1;
 }else if(lhs > rhs) {
  return 1;
 }else {
  return 0;
 }
})
 
console.log(array_num) // [7, 12, 12, 13, 55, 66, 564]
 
console.log("=======================");
 
array_num = [12,12,13,564,7,55,66];
 
//從大到小排序
 
array_num.sort(function (lhs,rhs) {
 
 if (lhs < rhs){
  return 1;
 }else if(lhs > rhs) {
  return -1;
 }else {
 return 0;
}
 
});
 
console.log(array_num) //[564, 66, 55, 13, 12, 12, 7]
 
console.log("=======================");

2.隨機打亂一個數(shù)組

array_num = [12,12,13,564,7,55,66];
 
array_num.sort(function () {
 
 if ( Math.random() < 0.5){
  return -1;
 }else {
  return 1;
 }
});
 
console.log(array_num); //[12, 12, 564, 13, 7, 66, 55] 隨機
 
console.log("=======================");

3.編寫程序 隨機的生存[10,100)范圍內(nèi)的整數(shù)

function random_int_num(start,end) {
 
 return Math.floor(start + (end - start) * Math.random());
 
}
 
console.log(random_int_num(10,100)); //69 隨機

關(guān)于“JS中使用數(shù)組的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI