创建
有以下几种方式
1.构造函数
在使用构造函数时,可以不带new
创建空数组
let color = new Array()
或者let color = Array()
创建指定个数元素的数组
let color = new Array(2)
或者let color = Array(2)
创建指定元素的数组
let color = new Array("black", "white")
或者let color = Array("black", "white")
2.数组字面量
使用数组字面量时,使用逗号会创建空串,默认值是undefined。对于空串,不同的方法作不同的处理,比如map会跳过空串,join会将空串当作空字符串
let color = ["black", "white"]
const options = [,,,,,]
console.log(options.length) //输出为5
console.log(options)//输出为[ <5 empty items> ]
for (let option of options) {
console.log(option)
}
//输出为
undefined
undefined
undefined
undefined
undefined
const options = [1,,,4]
console.log(options.map(x => 6))//输出为[ 6, <2 empty items>, 6 ]
const options = [1,,,4]
console.log(options.join('-'))//输出为1---4
3.静态方法
es6新增了创建数组的静态方法:Array.from和Array.of
Array.from的第一个参数是类数组对象,其第二个参数可选,类型为函数,作用是对于数组元素作映射。也可以接收第三个参数,用于指定映射函数中的this指向
console.log(Array.from("matt")) //输出为[ 'm', 'a', 't', 't' ]
const m = new Map().set(1, 2).set(3, 4)
console.log(Array.from(m)) //输出为[ [ 1, 2 ], [ 3, 4 ] ]
const m = new Set().add(1).add(2).add(3).add(4)
console.log(Array.from(m))//输出为[ 1, 2, 3, 4 ]
const a1 = [1, 2, 3, 4]
const a2 = Array.from(a1)
console.log(Array.from(a2))//输出为[ 1, 2, 3, 4 ]
const iter = {
*[Symbol.iterator](){
yield 1;
yield 2;
yield 3;
yield 4;
}
}
console.log(Array.from(iter))//输出为[1, 2, 3, 4]
function getArgsArray() {
return Array.from(arguments)
}
console.log(getArgsArray(1, 2, 3, 4))//输出为[1, 2, 3, 4]
const arrayLikeObject = {
0 : 1,
1 : 2,
2 : 3,
3 : 4,
length : 4
}
console.log(Array.from(arrayLikeObject))//输出为[ 1, 2, 3, 4 ]
const a1 = [1, 2, 3, 4]
const a2 = Array.from(a1, x => x ** 2)
console.log(a2)//输出为[ 1, 4, 9, 16 ]
const a1 = [1, 2, 3, 4]
const a2 = Array.from(a1, function(x) {
return x ** this.exponent
}, {exponent : 2})
console.log(a2)//输出为[ 1, 4, 9, 16 ]
Array.of用于将一组参数转为数组
console.log(Array.of(1, 2, 3, 4)) //输出为[ 1, 2, 3, 4 ]
console.log(Array.of(undefined)) //输出为[ undefined ]
Array.from应用在数组上时,其是浅复制
索引和长度
数组的索引从下标0开始,索引最大为数组长度-1。在设置时,如果指定的索引超过范围,会将数组的长度修改为索引值+1
如果修改数组的长度改为大于数组元素数,则添加的元素的值为undefined.
let color = ["red", "blue", "green"]
console.log(color.length) //输出为3
console.log(color[2]) //输出为green
color[3] = "black" //输出为4
console.log(color.length)
let color = ["red", "blue", "green"]
color.length = 2;
console.log(color[2]);//输出为undefined
let color = ["red", "blue", "green"]
color.length = 4;
console.log(color[3]);//输出为undefined
数组最大长度为4294967295,如果超过,会报错
let colors = new Array(4294967296);
或者
let colors = ["red", "blue", "green"]
colors.length = 4294967296;
会抛出
RangeError: Invalid array length
at Object.<anonymous> (f:\my_git_hub\OJ\vue\test.js:1:14)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
检测数组
使用静态方法Array.isArray
let colors = ["red", "blue", "green"]
console.log(Array.isArray(colors)) //输出为true
let colors = {a : 1}
console.log(Array.isArray(colors))//输出为false
迭代器方法
keys():返回数组索引的迭代器
values():返回数组元素的迭代器
entries():返回索引/元素对的迭代器
const a = ["foo", "bar", "baz", "qux"]
console.log(Array.from(a.keys()))//输出[ 0, 1, 2, 3 ]
console.log(Array.from(a.values()))//输出[ 'foo', 'bar', 'baz', 'qux' ]
console.log(Array.from(a.entries()))//输出[ [ 0, 'foo' ], [ 1, 'bar' ], [ 2, 'baz' ], [ 3, 'qux' ] ]
填充和复制
填充使用fill,其中开始索引参数是可选的,索引支持负值。在有结束索引参数时,是不包含结束位置的。在索引区间偏低或者偏高,填充操作被忽略。同时如果结束索引小于开始索引时,填充操作也被忽略。对于 索引区间部分可用情况时,只填充可用部分
const zeros = [0, 0, 0, 0, 0]
zeros.fill(5)
console.log(zeros) //输出为[ 5, 5, 5, 5, 5 ]
zeros.fill(0)
zeros.fill(5, 3)
console.log(zeros)//输出为[ 0, 0, 0, 5, 5 ]
zeros.fill(0)
zeros.fill(5, 1, 3)
console.log(zeros)//输出为[ 0, 5, 5, 0, 0 ]
zeros.fill(0)
zeros.fill(5, -4, -1)
console.log(zeros)//输出为[ 0, 5, 5, 5, 0 ]
zeros.fill(0)
zeros.fill(5, -10, -6)
console.log(zeros)//输出为[ 0, 0, 0, 0, 0 ]
zeros.fill(0)
zeros.fill(5, 6, 10)
console.log(zeros)//输出为[ 0, 0, 0, 0, 0 ]
zeros.fill(0)
zeros.fill(5, 6, 5)
console.log(zeros)//输出为[ 0, 0, 0, 0, 0 ]
zeros.fill(0)
zeros.fill(5, 3, 6)
console.log(zeros)//输出为[ 0, 0, 0, 5, 5 ]
zeros.fill(0)
复制使用copyWithin,复制指定范围内的元素,填充到指定索引开始的位置,与fill一样,也支持负索引,对于索引区间过低,过高,或者负长度区间忽略,对于部分区间可用的,复制可用部分
let ints, reset = () => ints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
reset()
ints.copyWithin(5)
console.log(ints)
reset()
//输出为
[
0, 1, 2, 3, 4,
0, 1, 2, 3, 4
]
ints.copyWithin(5, 3)
console.log(ints)
reset()
//输出为
[
0, 1, 2, 3, 4,
3, 4, 5, 6, 7
]
ints.copyWithin(5, 3, 6)
console.log(ints)
reset()
//输出为
[
0, 1, 2, 3, 4,
3, 4, 5, 8, 9
]
ints.copyWithin(-4, -7, -3)
console.log(ints)
reset()
//输出为
[
0, 1, 2, 3, 4,
5, 3, 4, 5, 6
]
ints.copyWithin(5, -15, -10)
console.log(ints)
reset()
//输出为
[
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
]
ints.copyWithin(5, 10, 15)
console.log(ints)
reset()
//输出为
[
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
]
ints.copyWithin(5, 10, 9)
console.log(ints)
reset();
//输出为
[
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
]
ints.copyWithin(5, 7, 15)
console.log(ints)
reset();
//输出为
[
0, 1, 2, 3, 4,
7, 8, 9, 8, 9
]
转换
toString:通过调用数组元素的toString得到字符串,然后使用逗号分隔符将所有字符串拼接
valueOf:返回数组本身
toLocaleString:调用数组元素的toLocalString得到字符串,然后用逗号分隔符拼接
join:用分隔符将数据拼接,在不传参数情况下或者传参为undefined,默认是使用逗号分隔符
对于 数组元素中有null或者undefined,toString,toLocaleString,join会将其作为空字符串来处理
let colors = ["red", "blue", "green"]
console.log(colors.toString()) //输出red,blue,green
console.log(colors.valueOf()) //输出[ 'red', 'blue', 'green' ]
let person1 = {
toLocaleString() {
return "Nikolaos";
},
toString() {
return "Nicholas";
}
};
let person2 = {
toLocaleString() {
return "Grigorios";
},
toString() {
return "Greg";
}
};
let people = [person1, person2]
console.log(people.toString()) //输出为Nicholas,Greg
console.log(people.toLocaleString())//输出为Nikolaos,Grigorios
let colors = ["red", "blue", "green"]
console.log(colors.join()) //输出为red,blue,green
console.log(colors.join(","))//输出为red,blue,green
console.log(colors.join("||"))//输出为red||blue||green
console.log(colors.join(undefined))//输出为red,blue,green
let colors = ["red", null, "blue", undefined, "green"]
console.log(colors.toString()) //输出为red,,blue,,green
console.log(colors.toLocaleString())//输出为red,,blue,,green
console.log(colors.join())//输出为red,,blue,,green
栈方法
push:将元素入栈,参数可以为任意个,返回是数组的长度
pop:从栈上弹出最后一个元素
let colors = new Array()
let count = colors.push("red", "blud")
console.log(count) //输出为2
count = colors.push("black")
console.log(count)//输出为3
let item = colors.pop()
console.log(item, colors.length)//输出为black 2
队列方法
shift:配合push来使用,是删除数组中的第一个并且返回该元素,数组长度减1
unshift:配合pop来使用,在数组的第一个位置添加元素,元素个数可以是任意个,并且返回数组长度
let colors = new Array()
let count = colors.push("red", "green")
console.log(count) //输出为2
count = colors.push("blue")
console.log(count)//输出为3
let item = colors.shift()
console.log(item)//输出为red
console.log(colors.length)//输出为2
let colors = new Array()
let count = colors.unshift("red", "green")
console.log(count)//输出为2
count = colors.unshift("blue")
console.log(count)//输出为3
let item = colors.pop()
console.log(item)//输出为green
console.log(colors.length)//输出为2
排序方法
reverse:将数组反向排序
sort:将数组根据比较规则排序,默认是按升序排列,对每个元素会调用String转型函数转为字符串再比较 ,可以接受比较函数
reverse和sort返回的是原数组的引用
let values = [1, 2, 3, 4, 5]
console.log(values.reverse()) //输出为[ 5, 4, 3, 2, 1 ]
let values = [0, 1, 5, 10, 15]
console.log(values.sort())//输出为[ 0, 1, 10, 15, 5 ]
let values = [0, 1, 5, 10, 15]
function compare(value1, value2)
{
if (value1 < value2) {
return -1
} else if (value1 > value2) {
return 1
} else {
return 0
}
}
console.log(values.sort(compare)) //输出为[ 0, 1, 5, 10, 15 ]
let afterSort = values.sort(compare)
console.log(afterSort === values) //输出为true
let afterReverse = values.reverse();
console.log(afterReverse === values)//输出为true
操作方法
concat:拼接成新数组,对原数组无影响。在拼接参数中,如果有参数类型为数组,而希望数组作为单个元素拼接,则需要将参数数组的Symbol.isConcatSpreadable设置为false
slice:根据起始和结束位置创建包含原数组对应元素的新数组,对原数组无影响 ,如果结束位置小于开始位置,返回空数组
splice:可以对数组添加(传3个参数,开始位置,0,要插入的元素),删除(2个参数,开始位置,要删除的元素个数),替换
let colors = ["red", "green", "blue"]
let colors2 = colors.concat("yello", ["black", "brown"])
console.log(colors) //输出为[ 'red', 'green', 'blue' ]
console.log(colors2)//输出为[ 'red', 'green', 'blue', 'yello', 'black', 'brown' ]
let colors = ["red", "green", "blue"]
let newColors = ["black", "brown"]
let moreNewColors = {
[Symbol.isConcatSpreadable] : true,
length: 2,
0: "pink",
1: "cyan"
};
newColors[Symbol.isConcatSpreadable] = false
let colors2 = colors.concat(newColors)
console.log(colors2)
//输出为
[
'red',
'green',
'blue',
[ 'black', 'brown', [Symbol(Symbol.isConcatSpreadable)]: false ]
]
let colors3 = colors.concat(moreNewColors)
console.log(colors3)
//输出为
[ 'red', 'green', 'blue', 'pink', 'cyan' ]
let colors = ["red", "green", "blue", "yellow", "purple"]
let colors2 = colors.slice(1)
let colors3 = colors.slice(1, 4)
console.log(colors2)//输出为[ 'green', 'blue', 'yellow', 'purple' ]
console.log(colors3)//输出为[ 'green', 'blue', 'yellow' ]
let colors = ["red", "green", "blue"]
let removed = colors.splice(0, 1)
console.log(colors)//输出为[ 'green', 'blue' ]
console.log(removed)//输出为[ 'red' ]
removed = colors.splice(1, 0, "yelllow", "orange")
console.log(colors) //输出为[ 'green', 'yelllow', 'orange', 'blue' ]
console.log(removed) //输出为[]
removed = colors.splice(1, 1, "red", "purple")
console.log(colors) //输出为[ 'green', 'red', 'purple', 'orange', 'blue' ]
console.log(removed)//输出为[ 'yelllow' ]
搜索和位置方法
indexOf:第一个参数是要查找的元素,第二个为可选参数,表示开始搜索位置,返回要查找元素在数组中的下标,没有找到时返回 -1。从开始位置向后查找
lastIndefOf:第一个参数是要查找的元素,第二个为可选参数,表示开始搜索位置,返回要查找元素在数组中的下标,没有找到时返回 -1。从数组尾开始向前查找
includes:第一个参数是要查找的元素,第二个为可选参数,表示开始搜索位置,数组中可以找到返回true,否则返回false
find和findIndex:第一个参数是断言函数,断言函数接收三个参数(element, index ,array),第二个参数表示断言函数内this的指向
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]
console.log(numbers.indexOf(4)) //输出为3
console.log(numbers.lastIndexOf(4))//输出为5
console.log(numbers.includes(4))//输出为true
console.log(numbers.indexOf(4, 4))//输出为5
console.log(numbers.lastIndexOf(4, 4))//输出为3
console.log(numbers.includes(4, 7))//输出为false
let person = {name : "Nicholas"}
let people = [{name : "Nicholas"}]
let morePeople = [person]
console.log(people.indexOf(person))//输出为-1
console.log(morePeople.indexOf(person))//输出为0
console.log(people.includes(person))//输出为false
console.log(morePeople.includes(person))//输出为true
const people = [
{
name: "Matt",
age: 27
},
{
name: "Nicholas",
age: 29
}
];
console.log(people.find((element, index, array) => element.age < 28))
//输出为{ name: 'Matt', age: 27 }
console.log(people.findIndex((element, index, array) => element.age < 28))//输出为0
迭代方法
every:数组中的每项都满足函数要求,则返回true
some:数组中只要有一项满足函数要求,则返回 true
filter:返回满足函数要求的元素组成的数组
map:数组中的每项都运行函数,新的元素组组成新的数组
forEach:数组中的每项都运行函数,无返回值
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]
let everyResult = numbers.every((element, index, array) => element > 2)
console.log(everyResult) //输出为false
let someResult = numbers.some((element, index, array) => element > 2)
console.log(someResult)//输出为true
let filterResult = numbers.filter((element, index, array) => element > 2)
console.log(filterResult)//输出为[ 3, 4, 5, 4, 3 ]
let mapResult = numbers.map((element, index, array) => element * 2)
console.log(mapResult)
//输出为
[
2, 4, 6, 8, 10,
8, 6, 4, 2
]
numbers.forEach((element, index, array) => console.log(element))
//输出为
1
2
3
4
5
4
3
2
1
归并方法
reduce:从数组第一项开始遍历到最后一项
reduceRight:从数组最后一项遍历到第一项
let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce((prev, cur, index, array) => prev + cur)
console.log(sum) //输出为15
let rightSum = numbers.reduceRight((prev, cur, index, array) => prev + cur)
console.log(rightSum)//输出为15