JavaScript常用数组

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值