关于JS的总结
数组遍历
1.
forEach
,遍历数组每一项,与
for
循环类似
let arr = [];
arr.forEach((item, index) => {
// item为当前遍历项
// index为当前遍历项的索引
})
2.
filter
,遍历过滤,返回一个新数组,不会修改原数组
const Arr = arr.filter((item, index) => {
// 返回满足条件的项,即item > 1的项
return item > 1;
})
3.
map
,遍历返回新数组,新数组中的每一项为
return
出来的值
const Arr = arr.map((item, index) => {
return 1;
})
console.log(Arr); // [1, 1, 1, ......]
数组增删改查
1.增
let arr = [1, 2];
// 在首部添加一个数组元素
//返回一个新的长度
arr.unshift(3); // [3, 1, 2]]
// 在尾部添加一个数组元素
//返回一个新的长度
arr.push(3); // [1, 2, 3]
2.删
// 在首部删除一个数组元素
// 返回值:被删除的项
arr.shift(); // arr = [2]
// 在尾部删除一个数组元素
arr.pop(); // arr = [1]
3.改
// 修改指定索引的数组元素
arr[2] = 3; // [1, 3]
4.查
// 查找数组元素中是否含有1;返回值boolean类型
arr.find(1); // true
// 查找指定索引下的数组元素
arr[1] // 2
截取
slice()
slice()
按照条件截取返回新数组
返回值
:返回一个新数组
是否改变原数组
:不改变
参数:
let ary5 = [1,2,3,4,5,6,7,8,9];
array.slice(n, m) // 从索引n开始查找到m处(不包含m)
array.slice(n) // 第二个参数省略,则一直查找到末尾
array.slice(0) // 原样输出内容,可以实现数组克隆
array.slice(-n,-m) // slice支持负参数,从最后一项开始算起,-1为最后一项,-2为倒数第二项
console.log(ary5.slice(2,8));//从索引2开始查找到索引为8的内容,结果为[3, 4, 5, 6, 7, 8]
console.log(ary5.slice(-2,-1));//[8]
数组转字符串
join()
join()
1.
arr.join('分隔符')
,参数可选,作为每个数组元素之间的份分隔符号
let arr = [a, c, 1, 3];
// 无分隔符情况
arr.join(); // 返回值:'ac13'
// 自定义分隔缝情况
arr.join('-'); // 返回值:'a-c-1-3'
多个数组合并
concat()
concat()
参数:参数可以是具体的值,也可以是数组对象。可以是任意多个
返回值:返回连接后的新数组
是否改变原数组:不改变
let ary = ['哈'];
let newAry = ary8.concat('喽');
console.log(newAry );//["哈", "喽"]
let arrConcat = arr.concat(['1', '2']); // ['哈', '1', '2']
数组增删改
splice()
splice()
增加
:ary.splice(n,0,m)从索引n开始删除0项,把m或者更多的内容插入到索引n的前面,返回空数组
修改
:ary.splice(n,x,m)从索引n开始删除x个,m替换删除的部分,把原有内容删除掉,然后用新内容替换掉
删除
:ary.splice(n,m) 从索引n开始删除m个内容,(如果第二个参数省略,则从n删除到末尾),返回删除的新数组,原有数组改变
//增加
let ary6_z = [33,44,55,66,77,88];
ary6_z.splice(2,0,'a','b')
console.log(ary6_z);// [33, 44, "a", "b", 55, 66, 77, 88]
//修改
let ary6_x = [33,44,55,66,77,88];
ary6_x.splice(1,2,'x','y')
console.log(ary6_x);// [33, "x", "y", 66, 77, 88]
//删除
let ary6_s = [33,44,55,66,77,88];
//console.log(ary6.splice(3,2))//[66, 77]
console.log(ary6_s.splice(3));//[66, 77, 88]
数组元素下标查询
检测当前值在数组中第一次出现的位置索引
参数
:array.indexOf(item,start) item:查找的元素 start:字符串中开始检索的位置
返回值
:第一次查到的索引,未找到返回-1
是否改变原数组
:不改变
let arr = ['a','b','c','d','e','a','f'];
// 从下标0开始往后查找元素'c'
console.log(arr.indexOf('c')); // 2
// 从下标3开始往后查找元素'a'
console.log(arr.indexOf('a',3)); // 5
检测当前值在数组中最后一次出现的位置索引
lastIndexOf()
lastIndexOf()
参数
:array.lastIndexOf(item,start) item:查找的元素 start:字符串中开始检索的位置
返回值
:第一次查到的索引,未找到返回-1
是否改变原数组
:不改变
let arr = ['a','b','c','d','e','a','f'];
console.log(arr.lastIndexOf('c')); // 2
console.log(arr.lastIndexOf('f', 1)); // -1
判断一个数组是否包含一个指定的值
includes()
includes()
参数
:指定的内容
返回值
:布尔值
是否改变原数组
:不改变
let ary13 = ['a','b','c','d'];
console.log(ary13.includes('c')); // true
console.log(ary13.includes('f')); // false
数组反转
reverse()
reverse()
返回值
:倒序后新数组
是否改变原数组
:改变
let ary12 = [6,8,10,12];
console.log(ary12.reverse()); // [12, 10, 8, 6]