JavaScript — — 数组 Array
数组方法 Array
方法 | 含义 | 返回值 |
---|---|---|
unshift() 1 | 在数组的头部增加一项 | 数组长度 |
shift() 1 | 从数组的头部删除一项 | 被删除的项 |
push()1 | 在数组的末尾添加一个新的元素 | 数组长度 |
pop()1 | 在数组的末尾删除一项 | 被删除的项 |
reverse()1 | 将一个数组逆序 | 逆序新数组 |
sort()1 | 用于对数组的元素进行排序 | 排序新数组 |
splice(pos,num,…)1 | 向数组删除添加替换项目 | 被截取掉的元素组成的新数组 |
concat() | 给数组连接新成员(数组或值,参数任意个) | 生成的新数组 |
join() | 将数组以参数作为间隔转换成字符串 | 参数间隔的字符串 |
toString() | 把数组转换为数组值(逗号分隔)的字符串 | 字符串 |
slice(start,end) | 用于截取一段数组中的成员 | 截取的新数组 |
fill(item,start,end)1 | 使用给定值填充一个数组 | |
copyWithin(target,start,end)1 | 复制数组自身并改变数组的元素 | 返回改变后的数组 |
.
sort(start,end)
如果不传递参数,会按照第一位数的数字从小到大排列;
如果传递参数,参数是一个函数,该函数有两个参数a,b,如果返回a-b则升序排列,如果返回b-a则降序排列。(适用于成员都是数字的情况)
eg:arr.sort(function(a, b){return a - b});
slice()
参数可以是负数,表示从后往前数
如果end>start,表示截取的是空数组
splice(pos,num,…):
pos:表示操作数组的位置;
num:表示要删除几项;
…:表示要向pos位置插入的元素。
补充:Math.min/max.apply([1, 2, 3]) 等于 Math.min/max(1, 2, 3);
·
·
·
javaScript改变原数组的方法
unshift()
,shift()
头增 头删
push()
,pop()
尾增 尾删
reverse()
,sort()
,splice()
反转排序增添换
fill()
,copyWithin()
ES6新增
ES5数组方法
indexOf()
- 在数组中搜索元素值
- 返回其位置——下标 or -1
arr.indexOf(item,start)
- 说明:indexOf方法比较时使用的是全等判定
lastIndexOf()
- 与 Array.indexOf() 类似,但是从数组结尾开始搜索
Array.lastIndexOf(item, start)
.
item:必需,要检索的项目;
start:可选,从哪里开始搜索。(负值将从结尾开始的给定位置开始,并搜索到开头)
forEach()
- 遍历数组,为每个数组元素调用一次函数(回调函数)
Array.forEach(function(item,index,array){})
.
item:遍历到的元素;
index:遍历到的下标;
array:数组本身
- 用于循环 参数是一个函数 该函数会执行arr.length次 无返回值
reduce()
- 归并,在每个数组元素上运行函数,以生成(减少它)单个值
var arr = [10, 20, 30, 40, 50];
var res = arr.reduce(function(total, value, index, array){
console.log(total + "," + value); //10,20/30.30/60,40/100,50
return total + value;
});
console.log(res); //150
total:总数(初始值/先前返回的值);
value:项目值;
index:项目索引;
array:数组本身
reduceRight()
- reduceRight() 方法在每个数组元素上运行函数,以生成(减少它)单个值。
Array.reduceRight(function(total, value, index, array){}
.
total:总数(初始值/先前返回的值);
value:项目值;
index:项目索引;
array:数组本身
- 参见 reduce(),从数组的最后一项开始,向前遍历到第一项
map()
- 映射,通过对每个数组元素执行函数来创建新数组
arr.map(function(item,value,array){})
.
item:数组成员;
index:索引;
array:数组本身
- 用于循环执行arr.length次(遍历—操作—返回),返回值是一个新数组 数组长度与原数组保持一致 数组的成员是参数函数的返回值
- map() 不会对空数组进行检测。
filter()
- 过滤,创建一个包含通过测试的数组元素的新数组
Array.filter(function(item,index,array){})
.
接收一个函数作为参数:item:成员;index:索引;array:数组本身;
- 该函数返回一个条件表达式 返回值是符合参数函数条件表达式的成员组成的数组
some()
- 检查某些数组值是否通过了测试或数组中是否有存在符合某种条件的成员
var arr = [1,2,"cherry",4,5,"apple"]
var result = arr.some(function(value, index, array) {
console.log(value); //1 / 2 /cherry
return typeof value === "string";
});
console.log(result); //true
接收一个函数作为参数:value:成员;index:索引;array:数组本身
- 断言方法 函数要有返回值 通常是符合某种条件的判定表达式
- 返回值一个布尔值 只要有任何一个成员符合了函数的描述 就返回真 都不符合才返回假
- 如果匹配成功 则返回true 后面不再进行遍历
every()
- 检查所有数组值是否通过测试.
Array.every(function(value, index, array) { return })
.
接收一个函数作为参数,value:成员;index:索引;array:数组本身
- 也是断言方法.函数要有返回值 通常是符合某种条件的判定表达式
- 返回值一个布尔值 只要有任何一个成员不符合函数的描述 就返回假 都符合才返回真
- 如果回调函数仅使用第一个参数(值)时,可以省略其他参数
·
·
·
ES6数组方法(2015)
Array.from()
静态方法
-
用于将两类对象转为真正的数组
- 类似数组的对象[array-like object](本质即必须有length属性)
- DOM操作返回的NodeList集合(如querySelectorAll方法返回的就是一个类数组对象)
- 函数内部的arguments对象
- 可遍历对象[iterable](包括ES6新增的数据结构Set 和Map)
-
只要是部署了Iterator接口的数据结构,Array.from都能将其转为数组(字符串也具有Iterator接口)
let arr = Array.from('w3cplus.com')
console.log(arr); //["w","3","c","p","l","u","s",".","c","o","m"]
let namesSet = new Set(['a', 'b'])
let arr2 = Array.from(namesSet)
console.log(arr2); //["a","b"]
关于参数:
如果参数是一个真正的数组,Array.from会返回一个一摸一样的新数组
可接受第二个参数,作用类似于数组的map方法,用来对于每个元素进行处理,并将处理后的值放入返回的数组
Array.from([5,2,6], x => x * x)
//等同于
Array.from([5,2,6]).map( x => x * x)
// [25,4,36]
- 使用Array.from()还可以返回各种数据类型
function typesOf () {
return Array.from(arguments, value => typeof value)
}
typesOf(null, [], NaN)
// <- ['object', 'object', 'number']
- 也可以使用map方法实现上面代码的功能:
function typesOf (...all) {
return all.map(value => typeof value)
}
typesOf(null, [], NaN)
// <- ['object', 'object', 'number']
Array.of
- 拓展运算符
(...)
也可以将某些数据结构转为数组(arguments对象,NodeList对象),背后调用的是遍历器接口(Symbol.iterator),即如果一个对象没有部署该接口,就无法转换
function cast (){
return [...arguments]
}
cast('a','b','c'); // ["a","b","c"]
// 该情况拓展运算符无法转换
Array.from({length:3})
// [undefined,undefined,undefined]
// 对于没有部署 Array.from方法的浏览器,可以用Array.prototype.slice方法替代
const toArray = (() =>
Array.from ? Array.from : obj => [].slice.call(obj)
)()
Array.of()
静态方法
- 用于将一组值转换为数组(主要是弥补构造函数Array()的不足,由于参数个数不同导致Array()行为有差异)
new Array()
// <- []
new Array(undefined)
// <- [undefined]
new Array(1)
// <- [undefined x 1]
new Array(3)
// <- [undefined x 3]
new Array(1, 2)
// <- [1, 2]
new Array(-1)
// <- RangeError: Invalid array length
- 基本上可以用来替代Array() 或 new Array(),且不存在由于参数不同导致的重载
Array.of()
// <- []
Array.of(undefined)
// <- [undefined]
Array.of(1)
// <- [1]
Array.of(3)
// <- [3]
Array.of(1, 2)
// <- [1, 2]
Array.of(-1)
// <- [-1]
- 总是返回参数值组成的数组。如果没有参数,就返回一个空数组
// Array.of 方法模拟实现
function ArrayOf () {
return [].slice.call(arguments)
}
find()
实例方法
- Array.prototype.find方法用于找出第一个符合条件的数组成员
Array.find(function(value, index, array){})
.
参数是一个回调函数:value: 项目值;
index:项目索引;
array:数组本身;
- 函数会遍历数组中的每个元素
- 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,即该数组项,之后的值不会再调用执行函数;如果没有符合条件的元素 返回 undefined
[1, 2, 3, 4, 5].find(item => item > 2)
// 3
[1, 2, 3, 4, 5].find((item, i) => i === 3)
// 4
[1, 2, 3, 4, 5].find(item => item === Infinity)
// undefined
- 对于空数组,函数不执行
findIndex()
- 用于查询数组中的成员的索引,返回通过测试函数的第一个数组元素的索引
Array.findIndex(function(value, index, array){})
.
接收一个函数作为参数:value: 项目值;
index:项目索引;
array:数组本身;
- 函数会遍历数组中的每个元素
- 数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引,之后的值不会再调用执行函数;否则 返回 -1
- 对于空数组,函数不执行
- 注:Array.prototype.find和Array.prototype.findIndex两个方法都可以发现NaN,弥补数组的indexOf方法的不足。
[NaN].indexOf(NaN)
// -1
[NaN].findIndex(y => Object.is(NaN, y))
// 0
fill()
- 使用给定值填充一个数组(适用于空数组的初始化,数组中已有的元素会全被抹去)
Array.fill(item,start,end)
.
item: 填充的内容;
start: 填充的起始位置(可选);
end: 填充的结束位置(可选)
['a', 'b', 'c'].fill(0)
// [0, 0, 0]
new Array(3).fill(0)
// [0, 0, 0]
['a', 'b', 'c',,,].fill(0, 2)
// ['a', 'b', 0, 0, 0]
new Array(5).fill(0, 0, 3)
// [0, 0, 0, undefined x 2]
- Array.prototype.fill提供的值可以是任意的,不仅可以是一个数值,甚至还可以是一个原始类型:
new Array(3).fill({})
// [{}, {}, {}]
// 这个方法不可以接受数组的映射方法,不过可以接受一个索引参数或类似下面这样的方式
new Array(3).fill(function foo () {})
// [function foo () {}, function foo () {}, function foo () {}]
- IE 11 及更早版本不支持 fill() 方法。
copyWithin()
- 在当前数组内部将指定位置的成员复制到其他位置(会覆盖原有成员)
Array.prototype.copyWithin(target, start = 0, end = this.length)
三个参数:target(必选):从该位置开始替换数据
start(可选):从该位置开始读取数据,默认为0。如果为负值,表示倒数
end(可选):到该位置前停止读取长度,默认等于数组长度。如果为负值,表示倒数
- 这三个参数都应该是数值,如果不是,会自动转为数值
// 对于没有部署 TypedArray 的 copyWithin 方法的平台
[].copyWithin.call(new Int32Array([1,2,3,4,5]), 0,3, 4)
// Int32Array[4, 2, 3, 4, 5]
keys()
- 用于遍历数组,对键名进行遍历
for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1
values()
- 用于遍历数组,对键值进行遍历
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
entries()
- 用于遍历数组,对键值对进行遍历
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"
- 如果不使用for…of循环,可以手动调用遍历器对象的next方法,进行遍历:
let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']
·
·
·
数组拓展
** 拓展运算符**(...)
~
2 数组的空位
- 数组的空位指数组的某一个位置没有任何值。
eg: Array构造函数返回的数组都是空位
Array(3) // [ , , , ]
空位不是undefined
0 in [undefined,undefined,undefined] // true
0 in [ , , , ] //false
即 第一个数组0号位有值,第二个数组0号位没有值
-
ES5中对空位的处理 — — 大多数情况会忽略空位
- forEach(),filter(),every(),some() — — 跳过空位
- map() — — 跳过空位,但保留这个值
- join()和toString() — — 将空位视为undefined,而undefined和null会被处理成空字符串
// forEach()
[,'a'].forEach((x,i) => console.log(i)) // 1
// fillter()
['a','b'].forEach(x => true) // ['a','b']
// every()
[,'a'].forEach(x => x === 'a') // true
// some()
[,'a'].forEach(x => x !== 'a') // false
// map()
[,'a'].forEach(x => 1) // [,1]
// join()
[,'a',undefined,null].join('#') // "#a##"
//toString()
[,'a',undefined,null].toString() // ",a,,"
- ES6中对空位的处理 — — 明确将空位转为undefined