一.创建数组
new Array(), 空数组
new Array(20), 长度20的数组
new Array("a","b","c"), 参数形成数组
Array.of(), 空数组
Array.of(20), 参数形成数组
Array.from('abc') //字符串转数组
Array.from(array[, mapFn, thisArg]); //数组转数组
//示例
var map = {
do() {
return n*2;
}
}
var a = Array.from([1, 2, 3], function(n){
return this.do(n);
}, map);
Array.from({ //属性名为数值并且有length属性的对象转数组
0: 'a',
1: 'b',
length: 2
})
二.数组方法
1.原数组改变
(1) push() 末尾添加,返回长度
(2) pop() 末尾移除,返回移除项
(3) unshift() 开头添加,返回长度
(4) shift() 开头移除,返回移除项
(5) sort(fun) 从小排到大(默认按字符串方式),返回原对象
可按自定义比较方法,根据返回正负数判断
function(a,b) { return a-b; }
(6) reverse() 反转数组项的顺序,返回原对象
(7) splice(delIndex, delNumber, addItem...)
删除并插入新元素,返回被删部分的新数组
(8) fill(value, startIndex[, endIndex]) 使用具体的值,填充指定序号范围,没有结束序号则默认数组尾末
(9) copyWithin(index, startIndex[, endIndex]) 复制后修改
index:待修改的序号起始 startIndex: 填充指定序号范围, 没有结束序号则默认数组尾末
2.原数组不变
(1) join(sep) 通过分隔符(默认逗号)连接成字符串
(2) toString 返回逗号连接的字符串
(3) concat() 原数组与多个元素或数组拼接,返回新数组
(4) slice(start, end) 切割原数组,返回被切部分的新数组,起止序号可用负数表示倒数
(5) indexOf(item,[start]) 从指定起点查找指定元素的序号
(6) lastIndexOf(item,[start]) 从末尾查找到指定起点,指定元素的序号
(7) includes(value) 是否包含指定值
遍历相关
(1) forEach(function(item,index,list){}) 遍历数组
(2) map(function(item){ return item; }) 处理数组每一项,形成新数组
(3) filter(function(item,index){ return true; }) 过滤数组每一项,形成新数组
(4) every(function(item) { return true; }) 判断数组是否所有项都满足条件,返回布尔结果
(5) some(function(item) { return true; }) 判断数组是否存在一项满足条件,返回布尔结果
(6) find(function(item) {return true;}) 查找符合条件的第一个元素
(7) findIndex(function(item){return true;}) 查找符合条件的第一个元素的序号
三.其他
length 数组长度
Array.isArray(obj) 判断对象是否数组
JS对象—2.工具函数(Array)
最新推荐文章于 2022-03-20 01:06:24 发布