Array()构造器
对于函数的定义而言,我感觉可以从函数的描述去理解记忆。函数所封装的功能往往就是其描述的内容。
- 数组字面量创建
let arr = [1,2];
console.log(arr.length);// 2
console.log(arr[0]); // 1
- 单个参数的Array()构造器
let arr = new Array(3);
console.log(arr.length); //3
console.log(arr[1]); //undefined
- 多个参数的Array()构造器
let arr = new Array('一', '二', '三');
console.log(arr.length); //3
console.log(arr[1]); // 二
静态属性
- 语法: Array[Symbol.species]
- 返回值 : Array 的构造函数
let arr = [];
console.log(arr[Symbol.species]); //undefined
console.dir(Array[Symbol.species]); //ƒ Array() { [native code] }
静态方法
Array.from()
- 语法 : Array.from(obj, mapFn, thisArg)
- obj: 想要转换成数组的伪数组对象或可迭代对象
- mapFn: 如果指定了该参数,新数组中的每个元素会执行该回调函数(可选)
- thisArg: 执行回调函数 mapFn 时 this 对象 (可选)
- 返回值 : 一个新的数组实例
**从String生成数组**
let obj = 'str'
let arr = Array.from(obj);
console.log(arr, typeof arr); //["s", "t", "r"] "object"
**从set生成数组**
let arr = [1, 1, 2, 3];
let set = new Set(arr);
console.log(set, set instanceof Array);
arr = Array.from(set, x => {
console.log(this);
return x + x;
});
console.log(arr);
/*
Set(3) {1, 2, 3} false
Window
Window
Window
(3) [2, 4, 6]
*/
**数组去重合并**
function combine() {
return Array.from(new Set(arguments));
}
let arr1 = [1, 1]
let arr2 = [2, 3]
let arr3 = combine(...arr1, ...arr2) //用到了三点运算符。
console.log(arr3)
// [1, 2, 3]
Array.isArray()
- 语法 : Array.isArray(obj)
- 返回值: 如果值是 Array,则为true; 否则为false。
let arr = [];
console.log(typeof arr, Array.isArray(arr));
// object true 解决了typeof 的弊端,对于数组的对象,我们希望它的类型检测是Array
Array.of()
- 语法:Array.of(任意个参数,将按顺序成为返回数组中的元素)
- 返回值: 新的 Array 实例
let arr1 = new Array(3);
let arr2 = Array.of(3);
console.log(arr1);
console.log(arr2);
实例属性
Array.length
let arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Object.defineProperty(arr, 'length', {
writable: false,
configurable: false,
enumerable: false
})
arr.length = 5;
console.log(arr.length)
/* 1
2
3
3 //通过defineProperty方法后,发现并不能修改
*/
let arr = [1, 2, 3];
arr.length = 5;
console.log(arr);
// [1, 2, 3, empty × 2]
// length的灵活,可以动态的修改。
实例方法
方法的语义化分类:
- 迭代器方法。
keys()、values()、entries()
. 用于检索数组内容的方法。返回一个迭代器的对象。 - 复制和填充方法。
fill()、copywith()
. 都是包含开始索引,不包含结束索引。(不会改变数组的大小) - 转换方法。
toLocaleString() 、 toString() 、 valueOf()
。这里要区分toLocaleString()。如果设置了toLocaleString(),则会调用它。而默认都会调用toString()。 - 栈方法。
push() 、 pop()
。符合栈的特性。 从数组最后面压入、弹出元素。 - 队列方法。
shift() 、 unshift()
。shift()是从数组最前面删除元素,其结合push()。就符合队列特性。unshift()和pop()结合。在相反方向,符合队列的特性。 - 排序方法:
reverse()、sort()
。注意sort(参数中的比较函数)。 - 操作方法 :
concat()、slice()、splice()
。 - 搜素和位置方法:
indexOf() 、lastIndexOf() 、includes() 、find() 、findIndex()
. - 迭代方法:
every()、filter()、forEach()、map()、some()
。 - 归并方法:
reduce()、reduceRight()
。迭代数组所有项。并在此基础上构建一个最终返回值。
对于实例方法中的一些需要下标参数的方法,**其下标取值为负数**的话。会计算:用数组的length - 你传的负参数 = 参数的实际下标。
const arr = [1, 2, 3, 4];
console.log(arr.copyWithin(0, -1));
// 4,2,3,4
const arr = [1, 2, 3, 4];
console.log(arr[-1], arr[4]);
//undefined undefined
Array.prototype.concat()
- 语法 : var new_array = old_array.concat(valueN)
- valueN(可选)
数组和/或值
,将被合并到一个新的数组
中。
- valueN(可选)
- 返回值 : 新的 Array 实例
var num1 = [1, 2, 3],
num2 = [4, 5, 6],
num3 = [7, 8, 9];
var nums = num1.concat(num2, num3);
console.log(nums);
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
let arr = [1, 2, [3, 4]];
let arr1 = [].concat(arr);
let arr2 = [].concat(1, 2, [3, 4]);
console.log(arr1);
console.log(arr2);
/*
[1, 2, Array(2)]
[1, 2, 3, 4]
*/
Array.prototype.copyWithin()
- 语法 :arr.copyWithin(target, start, end)
- 返回值:改变后的数组
const array1 = ['a', 'b', 'c', 'd', 'e'];
// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]
// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]
Array.prototype.entries()
- 语法 : Array.prototype.entries()
- 返回值 : 返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。(可以使用next()方法)
const array1 = ['a', 'b', 'c'];
const iterator1 = array1.entries();
console.log(iterator1.next().value);
// expected output: Array [0, "a"]
console.log(iterator1.next().value);
// expected output: Array [1, "b"]
Array.prototype.every()
- 语法 :arr.every(callback(element , index , array ) , thisArg )
- callback用来测试每个元素的函数,它可以接收三个参数:
- element。用于测试的当前值。
- index可选。用于测试的当前值的索引。
- array可选。调用 every 的当前数组
- thisArg 。执行 callback 时使用的 this 值
- callback用来测试每个元素的函数,它可以接收三个参数:
- 返回值 :如果回调函数的每一次返回都为 真值,返回 true ,否则返回 false。
- 描述 :
测试一个数组内的所有元素是否都能通过某个指定函数的测试
。它返回一个布尔值。
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// true .
// 若收到一个空数组,此方法在一切情况下都会返回 true。
Array.prototype.fill()
- 语法 : arr.fill(value , start , end)
- 返回值 : 修改后的数组
- 描述 : 用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引
const array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]
// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]
console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
Array.prototype.filter()
- 语法 : var newArray = arr.filter(callback(element , index , array ) , thisArg )
- callback 。 用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数:
- element。数组中当前正在处理的元素。
- index可选。正在处理的元素在数组中的索引。
- array可选。调用了 filter 的数组本身。
- thisArg可选。执行 callback 时,用于 this 的值
- callback 。 用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数:
- 返回值 :一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组
- 描述 :创建一个新数组, 其包含通过所提供函数实现的测试的所有元素
function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
Array.prototype.find()
- 语法 : arr.find(callback , thisArg )
- 返回值 :数组中第一个满足所提供测试函数的元素的值,否则返回 undefined
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// 12
Array.prototype.findIndex()
- 语法:arr.findIndex(callback , thisArg)
- 返回值:返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
Array.prototype.flat() (扁平化数组
)
- 语法: var newArray = arr.flat([depth])
- depth 可选 。指定要提取
嵌套数组的结构深度
,默认值为 1
- depth 可选 。指定要提取
- 返回值 :所有元素与遍历到的子数组中的元素合并为一个新数组返回.
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]
Array.prototype.forEach() ( 除了抛出异常以外,没有办法中止或跳出 forEach() 循环
。如果你需要中止或跳出循环,forEach() 方法不是应当使用的工具)
- 语法: arr.forEach(callback(currentValue , index , array ) , thisArg )
- callback。为数组中每个元素执行的函数,该函数接收一至三个参数:
- currentValue。数组中正在处理的当前元素。
- index 可选 。数组中正在处理的当前元素的索引。
- array 可选。forEach() 方法正在操作的数组。
- thisArg 可选。可选参数。当执行回调函数 callback 时,用作 this 的值
- callback。为数组中每个元素执行的函数,该函数接收一至三个参数:
- 返回值:undefined
- 描述:对数组的每个元素执行一次给定的函数
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
const arr = [10, 11, 12, 13];
let arr1 = [1, 2, 3];
arr.forEach(function(...arg) {
console.log(...arg);
});
/*
10 0 (4) [10, 11, 12, 13]
11 1 (4) [10, 11, 12, 13]
12 2 (4) [10, 11, 12, 13]
13 3 (4) [10, 11, 12, 13]
arg[0]结果
10
11
12
13
*/
Array.prototype.includes()
- 语法:arr.includes(valueToFind , fromIndex)
- valueToFind : 需要查找的元素值
- fromIndex : 从fromIndex 索引处开始查找 valueToFind。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜.默认为 0 .
- 返回值:返回一个布尔值 Boolean ,如果在数组中找到了(如果传入了 fromIndex ,表示在 fromIndex 指定的索引范围中找到了)则返回 true
- 描述: 来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false
const arr = [1, 2, 1, 3];
console.log(arr.includes(1, 1));
//true
[1, 2, NaN 或 undefined ].includes(NaN 或 undefined); // true
(function() {
console.log([].includes.call(arguments, 'a')); // true
console.log([].includes.call(arguments, 'd')); // false
})('a','b','c');
// 这里又应用到了call()方法。通过call()改变this指向。
Array.prototype.indexOf()
- 语法: arr.indexOf(searchElement , fromIndex)
- searchElement。要查找的元素
- fromIndex 可选。开始查找的位置。
- 返回值:
首个
被找到的元素在数组中的索引位置; 若没有找到则返回 -1
const arr = [1, '1', [1, 2], '[1,2]'];
console.log(arr.indexOf('[1,2]'));
// 3
// 采用“===”相同的策略,进行对比。
let arr = ['a', 'b', 'a', 'c', 'a', 'd'];
let arr1 = [];
let element = 'a';
let index = arr.indexOf(element);
while (index != -1) {
arr1.push(index);
index = arr.indexOf(element, index + 1);
}
console.log(arr1.forEach(x => console.log(x)));
/*
0
2
4
undefined 。因为函数没有return值时,会返回undefined
*/
Array.prototype.join()
- 语法:arr.join( 字符串 )
- 指定一个字符串来分隔数组的每个元素。如果需要,将分隔符转换为字符串。如果缺省该值,数组元素用逗号(,)分隔。如果separator是空字符串(""),则所有元素之间都没有任何字符
- 返回值:一个所有数组元素连接的
字符串
。如果 arr.length 为0,则返回空字符串
连接伪数组对象
function f(a, b, c) {
var s = Array.prototype.join.call(arguments);
console.log(s); // '1,a,true'
}
f(1, 'a', true);
Array.prototype.keys()
- 语法 :arr.keys()
- 返回值 : 一个新的 Array 迭代器对象
const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
for (const key of iterator) {
console.log(key);
}
/*
0
1
2
相比较于 Object.keys(arr) 函数
*/
Array.prototype.lastIndexOf()
- 语法:arr.lastIndexOf(searchElement , fromIndex )
对比于 indexOf() , 其是从后往前找
。
- 返回值:数组中该元素最后一次出现的索引,如未找到返回-1
const arr = [1, 2, 3, 3, 2, 1];
console.log(arr.indexOf(3));
console.log(arr.lastIndexOf(3));
/*
2
3
*/
Array.prototype.map()
- 语法:var new_array = arr.map(function callback(currentValue , index , array ) {
// Return element for new_array
} , thisArg) - 返回值: 一个由原数组每个元素执行回调函数的结果组成的新数组(
包括undefined
)
onst array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
Array.prototype.pop()
- 语法: arr.pop()
- 返回值:从数组中删除的元素(当数组为空时返回undefined)
**注意。当其用作判断时,会用其返回值来进行判断。所以数组会改变**
const arr = [1, 1, 1];
while (arr.length) {
if (arr.pop() === 1) console.log(arr.length);
}
/*
2
1
0
*/
Array.prototype.push()
- 语法: arr.push( elementN)
- 返回值:当调用该方法时,
新的 length 属性值
将被返回
let index = 1;
let arr = [];
while (index !== 3) {
arr.push(index);
index++;
}
arr.forEach(x => console.log(x));
// 1 2
Array.prototype.reduce()
- 语法:arr.reduce(callback(accumulator, currentValue , index , arra ) , initialValue )
- callback 。执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数:
- accumulator。累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue。
- currentValue。数组中正在处理的元素。
- index 可选。数组中正在处理的当前元素的索引。 如果提供了initialValue,则起始索引号为0,否则从索引1起始。
- array可选。调用reduce()的数组
- initialValue可选。
作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错
- callback 。执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数:
- 返回值:函数累计处理的结果
console.log([0, 1, 2, 3, 4].reduce(function(a, b, c, d) {
console.log(a, b, c, d);
return a + b;
}));
/*
0 1 1 (5) [0, 1, 2, 3, 4]
1 2 2 (5) [0, 1, 2, 3, 4]
3 3 3 (5) [0, 1, 2, 3, 4]
6 4 4 (5) [0, 1, 2, 3, 4]
10
*/
Array.prototype.reverse()
- 语法 : arr.reverse()
- 返回值 :颠倒后的数组
const arr = [1, 2, 3];
let arr1 = arr.reverse();
console.log(arr1);
arr1[2] = 5;
console.log(arr);
/*
(3) [3, 2, 1]
(3) [3, 2, 5]
*/
Array.prototype.shift()
- 语法:arr.shift()
- 返回值:从数组中删除的元素; 如果数组为空则返回undefined
- 描述:从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
Array.prototype.unshift()
- 语法:arr.unshift( elementN)
- 返回值:当一个对象调用该方法时,返回其 length 属性值
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// expected output: 5
console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
Array.prototype.slice()
- 语法: arr.slice( begin , end )
- 返回值: 一个含有被提取元素的新数组
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
const arr = [1, 2, {
name: 'fjh'
}]
let arr1 = arr.slice()
arr1[2].name = '更改'
console.log(arr1)
console.log(arr)
Array.prototype.some()
如果用一个空数组进行测试,在任何情况下它返回的都是false
- 语法: arr.some(callback(element , index , array ) , thisArg )
- 返回值: 数组中有至少一个元素通过回调函数的测试就会返回true;所有元素都没有通过回调函数的测试返回值才会为false.
const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// expected output: true
Array.prototype.sort()
- 语法: arr.sort([compareFunction])
- compareFunction 可选.用来指定按某种顺序进行排列的函数。
如果省略,元素按照转换为的字符串的各个字符的Unicode位点进行排序
- compareFunction 可选.用来指定按某种顺序进行排列的函数。
- 返回值: 排序后的数组。请注意,数组已原地排序,并且不进行复制
注意: 最好还是自定义比较函数。
(因为其默认是ascll码进行比较,且默认是升序。)
- 对于数字的比较而言。如果第一个数字的ascll码不同,就会导致31 在 4 前面。第一个数字不同则会去判断第二个数字的ascll码。
- 对于字符比较而言。也是如此。字符串的比较就会从比较第一个字符,相同则第二个字符。。。。。。
如果没有指定**比较函数的参数**
const arr = [1, 2, 3, 10]
console.log(arr.sort());
// (4) [1, 10, 2, 3]
**指定比较函数的参数**
function compare(a, b) {
if (a < b ) { // 按某种排序标准进行比较, a 小于 b
return -1;
}
if (a > b ) {
return 1;
}
// a must be equal to b
return 0;
}
//对于数值类型而言.
const arr = [1, 2, 10, 3];
console.log(arr.sort(function(a, b) {
return a - b; //由小到大
}))
// 1,2,3,10 . 由小到大. 如果a-b小于0的话.表示不需要根据由小到大的规则排序.
//对于字符类型而言.
const arr = ['A', 'a', 'b', 'G'];
console.log(arr.sort());
// A G a b
const arr = ["la", "lb", "lc"];
console.log(arr.sort(compare));
function compare(str1, str2) {
if (str1 > str2) {
return -1;
} else if (str1 < str2) {
return 1;
} else {
return 0;
}
}
//lc,lb,la
//
/*
数字0到9的ASCII码值分别为48到57
大写字母“A”到“Z”的ASCII码值分别为65到90
小写字母“a”到“z”的ASCII码值分别为97到到122
*/
Array.prototype.splice()
-
语法: array.splice(start , deleteCount , item…])
- start . 指定修改的开始位置(从0计数)
- deleteCount . 整数,表示要移除的数组元素的个数
- item… . 要添加进数组的元素,从start 位置开始。如果不指定,则 splice() 将只删除数组元素.
-
返回值 : 由被删除的元素组成的一个数组。如果只删除了一个元素,则返回只包含一个元素的数组。如果没有删除元素,则返回空数组
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// 运算后的 myFish: ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// 被删除的元素: ["angel", "clown"]
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var removed = myFish.splice(2, 0, 'drum', 'guitar');
// 运算后的 myFish: ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
// 被删除的元素: [], 没有元素被删除
Array.prototype.toString()
Array对象覆盖了Object的 toString 方法。.但是可以通过call()方法指定 数组对象去访问 Object对象上的toString()方法.
- 语法 : arr.toString()
- 返回值 : 一个表示指定的数组及其元素的字符串
const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// expected output: "1,2,a,1a"
Array.prototype.values()
Array.prototype.values === Array.prototype[Symbol.iterator] // true
- 语法: arr.values()
- 返回值: 一个新的 Array 迭代对象。
const array1 = ['a', 'b', 'c'];
const iterator = array1.values();
for (const value of iterator) {
console.log(value);
}
// expected output: "a"
// expected output: "b"
// expected output: "c"
var arr = ['a', 'b', 'c', 'd', 'e'];
var iterator = arr.values();
for (let letter of iterator) {
console.log(letter);
}
//"a" "b" "c" "d"
for (let letter of iterator) {
console.log(letter);
}
// undefined . 数组迭代器是一次性的, 或者说是临时对象.