因為一次只傳一個字串或數字太沒有效率,弄個集合包裝把所有資料放到裡面在一次傳過去。
在 JavaScript 可以放不同種類的資料型態,但其他語言程式不一定。
const list = ["a", "b","c", 1, 2, 3];
console.log(list[0]); //索引值都是從0開始計算,例如:要拿到資料字串"a"。
console.log(list.length) //6,陣列裡有6個元素
list[1] = "x"; //把x值指定給list[1],js會依據索引值把x送進去並修改成[ 'a', 'x', 'c', 1, 2, 3 ]
const list = ["a", "b","c", 1, 2, 3, "d"];
console.log(list[list.length - 1]); //無論加多少資料進去,我都可以拿到最後一筆資料
在陣列中又包陣列
let data = [
["a","b","c"],
[1,2,3,4],
["f","h"]
]
console.log(data[1][1]); //2
以下只會說明一些,詳請參考MDN 上的說明
新增:
const data = ["a", "b", "c", "d", "e"];
data.push(1);
console.log(data); //[ 'a', 'b', 'c', 'd', 'e', 1 ]
data.unshift(2)
console.log(data); //[2, 'a', 'b', 'c', 'd', 'e', 1 ]
刪除
const data = ["a", "b", "c", "d", "e"];
data.pop();
console.log(data); //[ 'a', 'b', 'c', 'd' ]
data.shift();
console.log(data); //[ 'b', 'c', 'd' ]
const list = [ 1, 2, 3, 4, 5];
let result = list.map(function(x){
return x * 2 ;
});
console.log(result); //[ 2, 4, 6, 8, 10 ]
與 map()差在 forEach()不會回傳新的陣列
const list = [1,2,3,4,5];
list.forEach(function(el){
console.log(el*2);
});
//2
//4
//6
//8
//10
const list = [1, 2, 3, 4, 5, 6, 7];
const result = list.filter(function(x){
return x % 2 == 1 ;
});
console.log(result); //[ 1, 3, 5, 7 ]
const data = ["a", "b", "c", "d", "e"];
data.splice(2,3) //從索引值2開始,刪掉3個元素
console.log(data); //["a","b"]
const data = ["a", "b", "c", "d", "e"];
data.splice(2,2,"x");
console.log(data); //[ 'a', 'b', 'x', 'e' ]
const data = ["a", "b", "c", "d", "e"];
data.splice(3,0,"x"); //從索引值3開始,刪除0個,並往前加入一個x
console.log(data); //[ 'a', 'b', 'c', 'x', 'd', 'e' ]
function myPush(arr, elm) {
arr.splice(arr.length,0,elm)
return arr
}
const data = ["a", "b", "c"]
const result = myPush(data, "x")
console.log(result) // ["a", "b", "c", "x"]
const list = [1, 2, 3, 4, 5, 6, 7];
const total = list.reduce(function(sum,num){
return sum + num;
},0); //0是初始值
console.log(total); //28
------------------------------
const list = [1, 4, 3, 9, 2, 6, 7, 8];
const total = list.reduce(function (acc, cv) {
if (cv > acc) {
return cv;
} else {
return acc;
}
})
console.log(total); //比大小最後cv會是9