8.1数组概览
数组是有序的下标从0开始
数组中的元素可以是不同类型
每个数组都有一个length属性
const arr1 = [1, 2, 3]; //整数数组
const arr2 = ["one", 2, "three"]; //非齐次数组
const arr3 = [ //包含数组的非齐次数组
[1, 2, 3],
["one", 2, "three"]
];
const arr4 = [{ //非齐次数组
name: "Fred",
type: "object",
luckyNumbers:[5, 7, 13]
},
[{
name: "Susan",
type: "object"
},
{
name: "Anthony",
type: "object"
}
], 1,
function() {
return "arrays can contain functions too";
}, "three"
];
//数组元素取值赋值
arr1[0] = "one";
arr2[2] = 3;
console.log(arr1[0]);
console.log(arr2[2]);
console.log(arr3[1]);
console.log(arr4[1][0]);
//获取数组长度
console.log(arr1.length);
console.log(arr4.length);
console.log(arr4[1].length);
//访问超过数组下标的元素
console.log(arr2[10]);
console.log(arr2.length);
//构造创建数组 很少用
const arr5 = new Array();
const arr6 = new Array(1, 2, 3);
const arr7 = new Array(2);
const arr8 = new Array("2");
8.2数组内容操作
方法 | 方法描述 | 修改数组或返回拷贝数组 |
---|---|---|
push(返回新数组的长度),pop | 创建一个栈(先进后出[LIFO]) | 修改数组 |
unshift(返回新数组的长度),shift | 创建一个队列(先进先出[FIFO]) | 修改数组 |
concat | 在数组末尾添加多个元素 | 返回数组拷贝 |
slice | 获取子数组 | 返回数组拷贝 |
splice | 在任意位置添加或删除元素 |
修改数组 |
copyWithin | 剪切并替换数组元素 |
修改数组 |
fill | 填充数组 | 修改数组 |
reverse | 反转数组 | 修改数组 |
sort(传入函数来进行自定义排序) | 数组排序 | 修改数组 |
console.log("=============添加和删除数组元素===================");
let arr = ["b", "c", "d"];
console.log(arr.toString());
//push和pop的作用分别是添加或者删除数组的最后一个元素
//push和pop是栈操作
console.log(arr.push("e"))
console.log(arr.pop());
//shift和unshift是删除和添加数组的第一个元素
//shift和unshift队列操作
console.log(arr.unshift("a"));
console.log(arr.shift());
console.log("=============合并追加数组===================");
console.log(arr.concat(4, 5, 6).toString());
console.log(arr.toString());
console.log(arr.concat([4, 5, 6]).toString());
console.log(arr.concat([4, 5], 6).toString());
console.log(arr.concat([
[4, 5], 6
]));
console.log("=============截取数组===================");
arr = [1, 2, 3, 4, 5];
console.log(arr.slice(3).toString());
console.log(arr.slice(2, 4).toString());
console.log(arr.slice(-2).toString());
console.log(arr.slice(1, -2).toString());
console.log(arr.slice(-2, -1).toString());
console.log(arr.toString());
console.log("=============任意位置添加和删除元素===================");
arr = [1, 5, 7]
// 下标 删除个数 添加元素
arr.splice(1, 0, 2, 3, 4).toString();
console.log(arr.toString());
arr.splice(5, 0, 6).toString();
console.log(arr.toString());
console.log(arr.splice(1, 2).toString());
console.log(arr.toString());
console.log(arr.splice(2, 1, 'a', 'b').toString());
console.log(arr.toString());
console.log("=============数组分割和替换===================");
arr = [1, 2, 3, 4];
// 目标 开始 结束
console.log(arr.copyWithin(1, 2).toString());
console.log(arr.toString());
console.log(arr.copyWithin(2, 0, 2).toString());
console.log(arr.copyWithin(0, -3, -1).toString());
console.log("=============填充数组===================");
arr = new Array(5).fill(1);
console.log(arr.toString());
console.log(arr.fill("a").toString());
console.log(arr.fill("b", 1).toString());
// 值 起始 结束
console.log(arr.fill("c", 2, 4).toString());
console.log(arr.fill(5.5, -4).toString());
console.log(arr.fill(0, -3, -1).toString());
console.log("=============数组的反转和排序===================");
arr = [1, 2, 3, 4, 5];
console.log(arr.reverse().toString());
console.log(arr.toString());
arr.sort();
console.log(arr.toString());
//指定排序函数
//sort还允许指定一个排序函数
arr = [{
name: "Sunzane"
}, {
name: "Jim"
}, {
name: "Trevor"
}, {
name: "Amanda"
}];
let compare = function(a, b) { //比较函数
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
}
let compare1 = (a, b) => { //比较函数
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
}
console.log(arr.sort( (a, b) => { //比较函数
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
}));
8.3数组的搜索
描述 | 方法 |
---|---|
元素的下标 | indexOf (简单的值),findIndex (复杂的值) |
最后一个元素的下标 | lastIndexOf ( 简单值) |
元素本身 | find |
数组中符合条件的元素 | some |
数组中所有元素都符合给定条件 | every |
const o = {
name: "Jerry"
};
let arr = [1, 5, "a", o, true, 5, [1, 2], "9"];
console.log("indexOf:"+arr.indexOf(5));
console.log("lastIndexOf:"+arr.lastIndexOf(5));
console.log("indexOf:"+arr.indexOf("a"));
console.log("lastIndexOf:"+arr.lastIndexOf("a"));
console.log("indexOf:"+arr.indexOf({
name: "Jerry"
}));
console.log("indexOf:"+arr.indexOf(o));
console.log("indexOf:"+arr.indexOf([1, 2]));
console.log("indexOf:"+arr.indexOf("9"));
console.log("indexOf:"+arr.indexOf(9));
// searchvalue start
console.log("indexOf:"+arr.indexOf("a", 5));
console.log("indexOf:"+arr.indexOf(5, 5));
console.log("lastIndexOf:"+arr.lastIndexOf(5, 4));
console.log("lastIndexOf:"+arr.lastIndexOf(true, 3));
arr = [{
id: 5,
name: "Judith"
}, {
id: 5,
name: "Francis"
}];
//findIndex 返回下标,找不到返回-1
console.log("findIndex:"+arr.findIndex(o => o.id === 5));
console.log("findIndex:"+arr.findIndex(o => o.name === "Francis"));
console.log("findIndex:"+arr.findIndex(o => o === 3));
console.log("findIndex:"+arr.findIndex(o => o.id === 17));
//find 返回数组中的元素,找不到返回undefined
console.log("find:"+arr.find(o => o.id === 5));
console.log("find:"+arr.find(o => o.id === 2));
arr = [5, 7, 12, 15, 17];
//判断某个值或者条件是否存在,存在为真,否则为假
console.log("some:"+arr.some(x => x % 2 === 0));
console.log("some:"+arr.some(x => Number.isInteger(Math.sqrt(x))));
arr = [4, 6, 16, 36];
//用于检测数组所有元素是否都符合指定条件
console.log("every:"+arr.every(x => x % 2 === 0));
console.log("every:"+arr.every(x => Number.isInteger(Math.sqrt(x))));
8.4数组转化
描述 |
方法 |
修改数组或返回拷贝数组 |
---|---|---|
转化数组中的所有元素 |
map | 返回数组拷贝 |
根据给定条件排除数组元素 |
filter | 返回数组拷贝 |
把整个数组转化成另一种数组类型 |
reduce | 返回数组拷贝 |
把元素转化成字符串并合并 |
join | 返回数组拷贝 |
任何时候如果数组格式与所需要的格式不一样,都可以用map和filter
map和filter都不会修改原始数组,而是返回数组的拷贝
const cart = [{
name: "Widget",
price: 9.95
}, {
name: "Gadget",
price: 22.95
}];
//姓名
const names = cart.map(x => x.name);
console.log(names.toString());
//价格
const prices = cart.map(x => x.price);
console.log(prices.toString());
//价格8折
const discountPrices = prices.map(x => x * 0.8);
console.log(discountPrices.toString());
//姓名全小写
const lcNames = names.map(x=>x.toLowerCase());
console.log(lcNames.toString());
//name和prices 合并成cartNew x name i下标
const cartNew = names.map((x,i)=>({name:x,price:prices[i]}));
console.log(cartNew);
//创建一副牌
const cards = [];
// 红桃 梅花 方块 黑桃
for (let suit of ['H', 'C', 'D', 'S']) {
for (let value = 1; value <= 13; value++) {
cards.push({
suit,
value
});
}
}
//找到所有2的纸牌
let val2 = cards.filter(c => c.value === 2);
console.log(val2);
//找到所有方块
const valD = cards.filter(c => c.suit === 'D');
console.log(valD);
//找到所有花色牌
const val10 = cards.filter(c => c.value > 10);
console.log(val10);
//找到所有红桃的花色牌
let valH10 = cards.filter(c => c.value > 10 && c.suit === 'H');
console.log(valH10);
function cardToString(c) {
const suits = {
'H': '\u2665',
'C': '\u2663',
'D': '\u2666',
'S': '\u2660'
};
const values = {
1: 'A',
11: 'J',
12: 'Q',
13: 'K'
};
for (let i = 2; i < 10; i++) {
values[i] = i;
}
return values[c.value] + suits[c.suit];
}
//找到所有2的纸牌
val2 = cards.filter(c => c.value === 2).map(cardToString);
console.log(val2);
//找到所有红桃的花色牌
valH10 = cards.filter(c => c.value > 10 && c.suit === 'H').map(cardToString);
console.log(valH10);
reduce可以转化整个数组。经常被用于将一个数组归纳成一个单独的值。
比如,对数组所有元素求和或者计算它们的平均值等
const arr = [5, 7, 2, 4];
//arr.reduce(function(prev,cur,index,arr){
// ...
//}, init);
//prev 必需 cur 必需 剩下都是可选
const sum = arr.reduce((a, x) =>{
console.log(a); // init 初始 累计的值
console.log(x);
return a + x
}, 0);
console.log(sum);
const words = ["Beachball", "Rodeo", "Angel",
"Aardvark", "Xylophone", "November", "Chocolate",
"Papaya", "Uniform", "Joker", "Clover", "Bali"
];
//首字母相同放一个数组里
const alphabetical = words.reduce((a, x) => {
if (!a[x[0]]) {
a[x[0]] = [];
}
a[x[0]].push(x);
return a;
}, {});
console.log(alphabetical);
const data = [3.3, 5, 7.2, 12, 4, 6, 10.3];
//半数值算法
const stats = data.reduce((a, x) => {
a.N++;
let delta = x - a.mean;
a.mean += delta / a.N;
a.M2 += delta * (x - a.mean);
return a;
}, {
N: 0,
mean: 0,
M2: 0
});
if (stats.N > 2) {
stats.variance = stats.M2 / (stats.N - 1);
stats.stdev = Math.sqrt(stats.variance);
console.log(stats.stdev);
}