数组:(Array)是一种可以按顺序保存数据的数据类型
数组的基本使用:
1、声明数组
1、字面量声明数组
let arr = [数据1 , 数据2 , 数据3 ,···, 数据n ]
2、使用new Array 构造函数声明
let arr = new Array(数据1 , 数据2 ,···, 数据n)
2、取值语法
数组名[下标]
3、遍历数组
for (let i=0 ; i<arr.length ; i++){
数组名[i]
}
4、操作数组
修改数组
新增数组
数组.push() 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
数组筛选
遍历旧数组,追加到新数组
数组删除
arr.pop() 方法从数组中删除最后一个元素,并返回该元素的值
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
// Expected output: "tomato"
console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage"]
arr.shift()方法从数组中删除第一个元素,并返回该元素的值
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// Expected output: Array [2, 3]
console.log(firstElement);
// Expected output: 1
arr.splice(删除的起始下标,删除的个数,需要替换的词) 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。
如果没有写删除个数,则默认删除到最后
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]
months.splice(4, 1);
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April"]