1. arrayoverview
array is JavaScript in用于store many 个值 has 序collection. array可以package含任意class型 data, includingnumber, string, object, 甚至otherarray.
array is JavaScript in最常用 datastructure之一, Masterarray operationmethod for 于writing high 效 JavaScript code至关 important .
2. array creation
JavaScript increationarray 方式 has many 种:
2.1 字面量语法
// using字面量语法creationarray
const fruits = ['苹果', '香蕉', '橙子'];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, 'hello', true, null, undefined];
2.2 Array constructfunction
// using Array constructfunctioncreationarray
const emptyArray = new Array();
const arrayWithLength = new Array(5); // creation long 度 for 5 空array
const arrayWithElements = new Array('a', 'b', 'c'); // creationpackage含指定元素 array
2.3 Array.of() method
// using Array.of() methodcreationarray
const numbers = Array.of(1, 2, 3, 4, 5);
const strings = Array.of('a', 'b', 'c');
2.4 Array.from() method
// using Array.from() method from classarrayobject or 可iterationobjectcreationarray
const str = 'hello';
const charArray = Array.from(str); // ['h', 'e', 'l', 'l', 'o']
// from Set creationarray
const set = new Set(['a', 'b', 'c']);
const setArray = Array.from(set); // ['a', 'b', 'c']
// from Map creationarray
const map = new Map([['a', 1], ['b', 2]]);
const mapArray = Array.from(map); // [['a', 1], ['b', 2]]
3. array元素 访问 and modify
array元素throughindexfor访问 and modify, index from 0 开始:
const fruits = ['苹果', '香蕉', '橙子'];
// 访问array元素
console.log(fruits[0]); // 输出: 苹果
console.log(fruits[1]); // 输出: 香蕉
console.log(fruits[2]); // 输出: 橙子
// modifyarray元素
fruits[1] = '葡萄';
console.log(fruits); // 输出: ['苹果', '葡萄', '橙子']
// 访问不存 in 元素
console.log(fruits[5]); // 输出: undefined
// 获取array long 度
console.log(fruits.length); // 输出: 3
4. array basicoperationmethod
4.1 添加 and delete元素
const fruits = ['苹果', '香蕉', '橙子'];
// push() - in array末尾添加元素
fruits.push('葡萄', '草莓');
console.log(fruits); // 输出: ['苹果', '香蕉', '橙子', '葡萄', '草莓']
// pop() - from array末尾delete元素
const lastFruit = fruits.pop();
console.log(lastFruit); // 输出: 草莓
console.log(fruits); // 输出: ['苹果', '香蕉', '橙子', '葡萄']
// unshift() - in array开头添加元素
fruits.unshift('樱桃', '梨');
console.log(fruits); // 输出: ['樱桃', '梨', '苹果', '香蕉', '橙子', '葡萄']
// shift() - from array开头delete元素
const firstFruit = fruits.shift();
console.log(firstFruit); // 输出: 樱桃
console.log(fruits); // 输出: ['梨', '苹果', '香蕉', '橙子', '葡萄']
4.2 array 拼接
const fruits = ['苹果', '香蕉', '橙子'];
// splice() - 添加/delete/replace元素
// 语法: splice(start, deleteCount, item1, item2, ...)
// delete元素
fruits.splice(1, 1); // from index 1 开始delete 1 个元素
console.log(fruits); // 输出: ['苹果', '橙子']
// 添加元素
fruits.splice(1, 0, '香蕉', '葡萄'); // from index 1 开始delete 0 个元素, 添加 new 元素
console.log(fruits); // 输出: ['苹果', '香蕉', '葡萄', '橙子']
// replace元素
fruits.splice(2, 1, '草莓'); // from index 2 开始delete 1 个元素, 添加 new 元素
console.log(fruits); // 输出: ['苹果', '香蕉', '草莓', '橙子']
4.3 array 连接 and 截取
const fruits1 = ['苹果', '香蕉'];
const fruits2 = ['橙子', '葡萄'];
// concat() - 连接 many 个array
const allFruits = fruits1.concat(fruits2);
console.log(allFruits); // 输出: ['苹果', '香蕉', '橙子', '葡萄']
// slice() - 截取array 一部分
// 语法: slice(start, end)
const fruits3 = allFruits.slice(1, 3);
console.log(fruits3); // 输出: ['香蕉', '橙子']
const fruits4 = allFruits.slice(2); // from index 2 开始 to 末尾
console.log(fruits4); // 输出: ['橙子', '葡萄']
5. array 遍历
5.1 for 循环
const fruits = ['苹果', '香蕉', '橙子'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// 输出:
// 苹果
// 香蕉
// 橙子
5.2 forEach() method
const fruits = ['苹果', '香蕉', '橙子'];
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
// 输出:
// 0: 苹果
// 1: 香蕉
// 2: 橙子
5.3 for...of 循环
const fruits = ['苹果', '香蕉', '橙子'];
for (const fruit of fruits) {
console.log(fruit);
}
// 输出:
// 苹果
// 香蕉
// 橙子
6. array 转换method
6.1 map() method
const numbers = [1, 2, 3, 4, 5];
// map() - creation一个 new array, 其结果 is 原arrayin 每个元素都调用一个providing function after 返回 结果
const doubled = numbers.map(num => num * 2);
console.log(doubled); // 输出: [2, 4, 6, 8, 10]
const squared = numbers.map(num => num ** 2);
console.log(squared); // 输出: [1, 4, 9, 16, 25]
6.2 filter() method
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// filter() - creation一个 new array, package含through所providingfunctionimplementation test 所 has 元素
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // 输出: [2, 4, 6, 8, 10]
const greaterThanFive = numbers.filter(num => num > 5);
console.log(greaterThanFive); // 输出: [6, 7, 8, 9, 10]
6.3 reduce() method
const numbers = [1, 2, 3, 4, 5];
// reduce() - for arrayin 每个元素执行一个由您providing reducer function, 将其结果汇总 for 单个return value
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // 输出: 15
const product = numbers.reduce((accumulator, currentValue) => {
return accumulator * currentValue;
}, 1);
console.log(product); // 输出: 120
7. array 搜索method
7.1 indexOf() and lastIndexOf()
const fruits = ['苹果', '香蕉', '橙子', '香蕉', '葡萄'];
// indexOf() - 返回 in arrayin可以找 to 一个给定元素 第一个index, such as果不存 in , 则返回 -1
const bananaIndex = fruits.indexOf('香蕉');
console.log(bananaIndex); // 输出: 1
// lastIndexOf() - 返回指定元素 in arrayin 最 after 一个 index, such as果不存 in 则返回 -1
const lastBananaIndex = fruits.lastIndexOf('香蕉');
console.log(lastBananaIndex); // 输出: 3
// 搜索不存 in 元素
const cherryIndex = fruits.indexOf('樱桃');
console.log(cherryIndex); // 输出: -1
7.2 find() and findIndex()
const users = [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 },
{ id: 3, name: '王五', age: 35 }
];
// find() - 返回arrayin满足providing testfunction 第一个元素 值
const user = users.find(user => user.age > 28);
console.log(user); // 输出: { id: 2, name: '李四', age: 30 }
// findIndex() - 返回arrayin满足providing testfunction 第一个元素 index
const userIndex = users.findIndex(user => user.age > 28);
console.log(userIndex); // 输出: 1
7.3 includes() method
const fruits = ['苹果', '香蕉', '橙子'];
// includes() - 用来判断一个array is 否package含一个指定 值
console.log(fruits.includes('香蕉')); // 输出: true
console.log(fruits.includes('葡萄')); // 输出: false
8. array sort
8.1 sort() method
const numbers = [5, 2, 1, 4, 3];
const fruits = ['橙子', '苹果', '香蕉'];
// sort() - for array 元素forsort
// 默认按照string Unicode 码点sort
fruits.sort();
console.log(fruits); // 输出: ['苹果', '橙子', '香蕉']
// numbersort需要比较function
numbers.sort((a, b) => a - b); // 升序
console.log(numbers); // 输出: [1, 2, 3, 4, 5]
numbers.sort((a, b) => b - a); // 降序
console.log(numbers); // 输出: [5, 4, 3, 2, 1]
8.2 reverse() method
const fruits = ['苹果', '香蕉', '橙子'];
// reverse() - 颠倒arrayin元素 顺序
fruits.reverse();
console.log(fruits); // 输出: ['橙子', '香蕉', '苹果']
9. array Practicalmethod
9.1 isArray() method
// isArray() - 用于确定传递 值 is 否 is a Array
console.log(Array.isArray([1, 2, 3])); // 输出: true
console.log(Array.isArray({})); // 输出: false
console.log(Array.isArray('hello')); // 输出: false
9.2 join() method
const fruits = ['苹果', '香蕉', '橙子'];
// join() - 将array 所 has 元素连接成一个string
const fruitsString = fruits.join(', ');
console.log(fruitsString); // 输出: 苹果, 香蕉, 橙子
const fruitsString2 = fruits.join(' - ');
console.log(fruitsString2); // 输出: 苹果 - 香蕉 - 橙子
9.3 flat() and flatMap() method
const nestedArray = [1, 2, [3, 4, [5, 6]]];
// flat() - 按照一个可指定 深度递归遍历array, 并将所 has 元素 and 遍历 to 子arrayin 元素merge for 一个 new array返回
const flattenedArray = nestedArray.flat(2);
console.log(flattenedArray); // 输出: [1, 2, 3, 4, 5, 6]
// flatMap() - 首先usingmapfunctionmap每个元素, 然 after 将结果压缩成一个 new array
const numbers = [1, 2, 3];
const doubledAndFlattened = numbers.flatMap(num => [num, num * 2]);
console.log(doubledAndFlattened); // 输出: [1, 2, 2, 4, 3, 6]
实践case: arraydataprocessing
fake设我们 has 一组学生成绩data, 需要for以 under processing:
- 计算所 has 学生 平均成绩
- 找出成绩 high 于 90 分 学生
- 将成绩 from high to low sort
- statistics各分数段 学生人数
const students = [
{ name: '张三', score: 85 },
{ name: '李四', score: 92 },
{ name: '王五', score: 78 },
{ name: '赵六', score: 95 },
{ name: '钱七', score: 88 }
];
// 1. 计算平均成绩
const totalScore = students.reduce((sum, student) => sum + student.score, 0);
const averageScore = totalScore / students.length;
console.log(`平均成绩: ${averageScore}`);
// 2. 找出成绩 high 于 90 分 学生
const highScorers = students.filter(student => student.score > 90);
console.log('成绩 high 于 90 分 学生:', highScorers);
// 3. 将成绩 from high to low sort
const sortedStudents = [...students].sort((a, b) => b.score - a.score);
console.log('成绩sort:', sortedStudents);
// 4. statistics各分数段 学生人数
const scoreRanges = {
'90-100': 0,
'80-89': 0,
'70-79': 0,
'60-69': 0,
'0-59': 0
};
students.forEach(student => {
const score = student.score;
if (score >= 90) scoreRanges['90-100']++;
else if (score >= 80) scoreRanges['80-89']++;
else if (score >= 70) scoreRanges['70-79']++;
else if (score >= 60) scoreRanges['60-69']++;
else scoreRanges['0-59']++;
});
console.log('分数段statistics:', scoreRanges);
互动练习: arrayoperation
请completion以 under arrayoperationtask:
- creation一个package含 1 to 10 array
- 计算arrayin所 has 元素 and
- creation一个 new array, package含原arrayin所 has 偶数 平方
- 将 new array按降序sort
请 in under 方输入你 code: