数组的内置方法
实例方法:at()
const array1 = [5, 12, 8, 130, 44];
//返回指定位置的值 ,如果是负数 指定的位置为array1.length + (负值)
array1.at(2); // 8
array1.at(-2); // 130. // array1.length -2
array1.at(-10); //undefined
//通过索引直接读取值
array1[2] // 8
//负数时和at方法有所不同
array1[-2] // undefined
实例方法:concat()
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
// 结果是返回新数组
console.log(array3);
// Array ["a", "b", "c", "d", "e", "f"]
//不改变原数组array1
console.log(array1) // Array ["a", "b", "c"]
console.log(array2) // Array ['d', 'e', 'f']
实例方法:copyWithin()
Array.prototype.copyWithin(target, start = 0, end = this.length)
//target(必需):从该位置开始替换数据。如果为负值,表示倒数。
//start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。
//end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算。
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3); // [4, 5, 3, 4, 5]
console.log(arr)// [4, 5, 3, 4, 5] //返回的是原数组,即改方法改变原数组
//两个参数
const arr1 = [1, 2, 3, 4, 5];
arr1.copyWithin(0, 3, 4); // [4, 5, 3, 4, 5]
实例方法:entries(),keys() 和 values()
//entries(),keys()和values()——用于遍历数组。它们都返回一个遍历器对象
for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
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']
实例方法:every()
//返回值类型:布尔值 true or false , 用于判断是否数组所有元素都满足某一条件
const isBelowThreshold = (currentValue,index,arr) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// true
实例方法:some()
//返回值类型:布尔值 true or false , 用于判断是否数组部分元素都满足某一条件
const isBelowThreshold = (currentValue,index,arr) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.some(isBelowThreshold));
// true
实例方法:filter()
//过滤出满足指定条件的值,返回新数组
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word,index,arr) => word.length > 6);
console.log(result);
// Array ["exuberant", "destruction", "present"]
实例方法:map()
// 根据所有数组项map出一个新数组
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map((x,index,arr) => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
实例方法:forEach()
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// 'a'
// 'b'
// 'c'
// for 循环支持 break; continue;
for (let i = 0, len = array1.length; i<len; i++ ){
// break;
//continue
}
实例方法:reduce()
//使用数组项进行累加操作,支持指定初始累加值
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(previousValue, currentValue,index,arr) => previousValue + currentValue,
initialValue
);
console.log(sumWithInitial);
// expected output: 10
实例方法:reduceRight()
//从数组右侧开始进行reduce操作 ,支持指定初始累加值
const array1 = [[0, 1], [2, 3], [4, 5]];
const result = array1.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue));
console.log(result);
// expected output: Array [4, 5, 2, 3, 0, 1]
实例方法:find()
// 查找数组中满足条件的第一个值 , 如果没有找到则返回 undefined
[1, 4, -5, -6 , 10].find((n) => n < 0) // -5
实例方法:findIndex()
// 查找数组中满足条件的第一个值的索引 , 如果没有找到则返回 -1
[1, 4, -5, -6 , 10].findIndex((n) => n < 0) // 2
//第2之后开始有有效寻找
[1, 4, -5, -6 , 10].findIndex((n,index) => n < 0 && index>1 )
//使用indexOf查找具体值的位置
[1, 4, -5, -6 , 10].indexOf(-5) // 2
实例方法:findLast()
// 从数组末尾开始查找数组中满足条件的第一个值 , 如果没有找到则返回 undefined
[1, 4, -5, -6 , 10].findLast((n) => n < 0) // -6
实例方法:findLastIndex()
// 查找数组中满足条件的第一个值的索引 , 如果没有找到则返回 -1
[1, 4, -5, -6 , 10].findlastIndex((n) => n < 0) // 3
实例方法 : inlcudes()
// 语法 arr.includes(valueToFind[, fromIndex])
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat',1));
// expected output: false
console.log(pets.includes('at'));
// expected output: false
实例方法:push()
//从数组的右侧推入一个值 , 返回的值是新的数组长度
const arr=[1];
const b=arr.push(2);
console.log(arr);// [1,2]
console.log(b);// 2
实例方法:unshift()
//从数组的左侧推入一个值 , 回的值是新的数组长度
const arr=[1];
const b=arr.unshift(3);
console.log(arr);// [2,1]
console.log(b);// 2
实例方法:pop()
//从数组右侧弹出一个值,返回弹出的值
const arr=[1,3];
const b=arr.pop();
console.log(b); // 2
console.log(arr); // []
实例方法:shift()
//从数组左侧弹出一个值,返回弹出的值
const arr=[1,2];
const b=arr.shift();
console.log(b); // 1
console.log(arr); // [2]
实例方法:slice()
//使用当前数组复制出一个新数组 slice(startIndex[,endIndex])
const arr=[1,2];
arr1 = arr.slice(0);
console.log(arr1);// [1,2] 不指定endIndex默认到arr.length-1
console.log(arr===arr1); // false
console.log(arr.slice(1,2)) // [2]
实例方法:splice()
//使用当前数组裁剪出一个新数组,并改变原数组 splice(startIndex,length,replace)
const arr = [1,2,3,4];
const arr1 = arr.splice(1,2); // 在起始位置1的后面裁剪2个数组元素
console.log(arr1);// [2,3]
console.log(arr);// [1,4]
//向数组插入值
const arr = [1,2,3,4];
arr2 = arr.splice(1,2,0); //arr2: [1,4]
console.log(arr) // [1,0,4]
实例方法:sort()
//对数组元素进行排序 , 改变并返回原数组
const arr=[3,2,1,4];
arr.sort(); //默认升序 [1,2,3,4]
arr===arr.sort() // true
//根据排序函数进行排序
arr.sort((pre,next)=>{return pre-next}); //升序排序 [1,2,3,4]
arr.sort((pre,next)=>{return next-pre}); //降序排序 [4,3,2,1]
// 升序排序对象组成的数组,
function sortObjArrAccording(arr,prop){
return arr.sort((pre,next)=>{
return pre[prop]-next[prop]
})
}
const arr=[{name:'王二',age:30},{name:'孙武',age:20}];
sortObjArrAccording(arr,'age') ; [{name:'孙武',age:20},{name:'王二',age:30}];
实例方法:reverse()
//数组反转并返回原数组
const arr=[1,2,3];
arr1 = arr.reverse();// [3,2,1]
console.log(arr1===arr); // true
实例方法:fill()
//语法:array.fill(value, start, end)
//填充数组,并返回原数组
const arr=[1,2,3];
const b1=arr.fill(0);// [0,0,0]
console.log(arr===b1); //true
// 例子2
const arr=new Array(3);
arr.fill(0);
console.log(arr);// [0,0,0]
实例方法:join()
// 根据指定的separator连接数组所有的项并返回字符串
const arr=[1,2,3];
console.log(arr.join('-')); // 1-2-3
console.log(arr.join('')); // 123
实例方法:flat()
// 展开原数组并返回一个新数组
const arr = [1, 2, [3, [4, 5]]];
const arr1 = arr.flat() // 默认展开一层
// [1, 2, 3, [4, 5]]
console.log(arr1===arr); //false
//展开两层
arr=[1, 2, [3, [4, 5]]].flat(2);
console.log(arr);// [1, 2, 3, 4, 5]
实例方法:flatMap()
//flatMap()方法对原数组的每个成员执行一个函数(相当于执行Array.prototype.map()),
//然后对返回值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组。
[1, 2, 3, 4].flatMap(x => [[x * 2]])
// [[2], [4], [6], [8]]
实例方法:toString()
//toString() 方法返回包含所有数组值的字符串,以逗号分隔。
const arr = [1, 2, 'a', '1a'];
console.log(array1.toString());
// expected output: "1,2,a,1a"
const arr = [1, 'a', new Date('2020-10-10')];
console.log(array1.toString() )
//'1,a,Sat Oct 10 2020 08:00:00 GMT+0800 (中国标准时间)'
实例方法:toLocalString()
//首先调用每个数组元素的 toLocaleString() 方法,然后使用地区特定的分隔符把生成的字符串连接起来,形成一个字符串。
const array1 = [1, 'a', new Date('2020-10-10')];
array1.toLocaleString();
// '1,a,2020/10/10 08:00:00'
array1.toString();
//'1,a,Sat Oct 10 2020 08:00:00 GMT+0800 (中国标准时间)'
Array.of()
//Array.of()方法用于将一组值,转换为数组。
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
Array.of(undefined) // [undefined]
Array.from()
//Array.from()方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)
//和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// ES6 的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
// 例子2
// arguments 类数组对象
function foo() {
var args = Array.from(arguments);
}
//例子3 NodeList
let ps = document.querySelectorAll('p');
Array.from(ps).filter(p => {
return p.textContent.length > 100;
});
// 例子4 字符串
Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']
//例子5 转化Set集合为数组
let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']
Array.isArray()
//判断是否是数组
Array.isArray([1, 2, 3]); // true
Array.isArray({foo: 123}); // false
Array.isArray('foobar'); // false
Array.isArray(undefined); // false
//bad
const isArray=Object.prototype.toString.call([])==='[object Array]' // true
//good
const isArray=Array.isArray([]) // true
ArrayBuffer 对象
/**
ArrayBuffer对象、TypedArray视图和DataView视图是 JavaScript 操作二进制数据的一个接口
ArrayBuffer对象代表储存二进制数据的一段内存,它不能直接读写,只能通过视图(TypedArray视图和DataView视图)来读写,视图的作用是以指定格式解读二进制数据
**/
//ArrayBuffer也是一个构造函数,可以分配一段可以存放数据的连续内存区域。
const buf = new ArrayBuffer(32); //成了一段 32 字节的内存区域,每个字节的值默认都是 0
//创建并使用dataView 从头读取 8 位二进制数据
const buf = new ArrayBuffer(32);
const dataView = new DataView(buf);
dataView.getUint8(0) // 0
ArrayBuffer.prototype.byteLength
const buffer = new ArrayBuffer(32);
buffer.byteLength
// 32
ArrayBuffer.prototype.slice()
//拷贝buffer对象的前 3 个字节(从 0 开始,到第 3 个字节前面结束),生成一个新的ArrayBuffer对象
const buffer = new ArrayBuffer(8);
const newBuffer = buffer.slice(0, 3);
ArrayBuffer.isView()
//判断参数是否为TypedArray实例或DataView实例
ArrayBuffer.isView(buffer) // false
const v = new Int32Array(buffer);
ArrayBuffer.isView(v) // true