let list = [10, 20, 30, 40, 50, 40, 30, 20, 10, 11];
// 又返回值
let newList1 = list.map((item) => {
if (item > 10) return item;
return "";
})
console.log(newList1); // ['', 20, 30, 40, 50, 40, 30, 20, '', 11]
// 无返回值(所循环到的元素、下标、遍历的数组)
list.forEach((item, index, array) => {
console.log(item, index, array); // 10 0 [10, 20, 30, 40, 50, 40, 30, 20, 10, 11]
})
// 过滤数组
const newList2 = list.filter((item) => item > 11);
console.log(newList2); // [20, 30, 40, 50, 40, 30, 20]
// 有一项返回 true ,则整体为 true
const age = list.some((item) => {
return item > 100;
})
console.log(age); // 没有符合的:false
// 有一项返回 false ,则整体为 false
const age1 = list.every((item) => {
return item > 100;
})
console.log(age1); // 没有符合的:false
// 通过指定连接符生成字符串
const newList3 = list.join('-');
console.log(newList3); // 10-20-30-40-50-40-30-20-10-11
// 尾部添加元素
const newList4 = list.push(20);
console.log(newList4); // 返回所添加的元素
console.log(list); // [10, 20, 30, 40, 50, 40, 30, 20, 10, 11, 20]
// 移除最后一个数组元素 有返回值为数组删除掉的元素
list.pop();
console.log(list);
// 头部添加元素
list.unshift(1);
console.log(list); // [1, 10, 20, 30, 40, 50, 40, 30, 20, 10, 11]
// 删除头部元素
list.shift();
console.log(list); // [10, 20, 30, 40, 50, 40, 30, 20, 10, 11]
// 排序数组(默认为数字大小排序)改变原数组
const newList5 = list.sort();
console.log(newList5); // [10, 10, 11, 20, 20, 30, 30, 40, 40, 50]
// 反转数组(改变原数组)
const newList6 = list.reverse();
console.log(newList6); // [50, 40, 40, 30, 30, 20, 20, 11, 10, 10]
// 连接数组(可用于浅拷贝)
let list1 = [1000, 3200];
const newList7 = list.concat(list1);
console.log(newList7); // [50, 40, 40, 30, 30, 20, 20, 11, 10, 10, 1000, 3200]
// 截断数组
const newList8 = list.slice(1, 3);
console.log(newList8); // [40, 40]
// 查找数组项
const newList9 = list.indexOf(10000);
console.log(newList9); // -1(数组元素不存在返回-1)
// 计算属性
const newList10 = list.reduce((prev, cur) => {
return prev + cur;
})
console.log(newList10); // 261
JavaScript常用数组
于 2022-02-27 23:05:14 首次发布