//1.創(chuàng)建數(shù)組
var myArray1 = [1,2,3,354,5,20];
var myArray2 = [2,3,5,123,6,21];
//數(shù)組的連接方法concat()
var myArray3 = myArray1.concat(myArray2);
console.log(myArray3); ? ? //[1, 2, 3, 354, 5, 20, 2, 3, 5, 123, 6, 21]
//給數(shù)組的尾部添加一個元素push()
var length1 = myArray1.push("20");
console.log(myArray1); ? ? //[1, 2, 3, 354, 5, 20, "20"]
console.log(length1); ? ? //7
//給數(shù)組頭部添加一個元素unshift()
var length2 =? myArray2.unshift(20);
console.log(myArray2); ? ?//[20, 2, 3, 5, 123, 6, 21]
console.log(length2); ? ?//7
注意:凡是數(shù)組中添加元素都是返回數(shù)組的長度
//刪除尾部的元素pop()
var delSym1 = myArray1.pop();
console.log(myArray1);? ? //[1, 2, 3, 354, 5]
console.log(delSym1); ? ?//20
//刪除頭部元素shift()
var delSym2 = myArray2.shift();
console.log(myArray2);? //[3, 5, 123, 6, 21]
console.log(delSym2); ? ?//2
注意:凡是刪除元素都是返回刪除的元素
//刪除某一個位置的元素splice(2,4)
myArray1.splice(2,4);
console.log(myArray1);? ? //[1, 2]
注意:一般這個方法有兩個參數(shù)闺金,第一個表示從某一個位置開始刪除,第二個表示刪除元素的個數(shù)
//可以使用傳入的參數(shù)來連接每一個數(shù)組中的元素钱反,形成一個字符串join('-')
var lastString = myArray2.join('-');
console.log(typeof lastString);? //string
console.log(lastString);? //2-3-5-123-6-21
//將有規(guī)律的字符轉化成數(shù)組,使用參數(shù)中傳入的值進行分割split('-')
var lastArray = lastString.split('-');
console.log(lastArray);? ? //["2", "3", "5", "123", "6", "21"]
//按數(shù)字排序掖看,使用匿名函數(shù),傳入兩個形式參數(shù)面哥,當調用的時候哎壳,會把對應數(shù)組中的元素傳遞進來進行比較,如果返回時正值尚卫,就表示從小到大排序归榕,如果返回負值,表示從大到小排序
myArray1.sort(function(a,b) {
//? ? ? ? return a > b? 1:-1; ?//從小到大
? ? ? ? ? returna > b? -1:1; ? //從大到小
})
console.log(myArray1);? ? //[354,20,5,3,2,1]?