<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数值的扩展</title>
</head>
<body>
<script>
//1.扩展运算符(...)将一个数组转为用逗号分割的参数系列
console.log(...[1,2,3]);//1 2 3
//eg
const arr=[14,3,77]
//es5
console.log(Math.max.apply(null,arr));//77
//es6
console.log(Math.max(...arr));//77
//push()
var arr1=[1,2,3];
var arr2=[3,4,5]
console.log(Array.prototype.push.apply(arr1,arr2));
//es5
let arr3=[0,2,3];
let arr4=[4,5,6];
console.log(arr3.push(...arr4));
//合并数组(浅拷贝)
console.log(...arr3,...arr4);//0 2 3 4 5 6 4 5 6
//扩展运算符还可以将字符串转为真正的数组
console.log([...'hello']);//(5) ['h', 'e', 'l', 'l', 'o']
//2.Array.from()将类似数组转换为真的数组
//只要是部署了Iterator接口的数据结构,Array.from都能将其转为数组
console.log(Array.from('hello'))//(5) ['h', 'e', 'l', 'l', 'o']
let nameSet=new Set(['a,b'])
console.log(Array.from(nameSet));//['a,b']
//3.Array.of()方法用于将一组值,转换为数组
// const A=(3,8,11);
console.log(Array.of(3,8,11));//(3,8,11)
//4.数组实例的 copyWithin()在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方法,会修改当前数组。
// Array.prototype.copyWithin(target,start=0,end=this.length)
const A=[1,2,3,4,5]
console.log(A.copyWithin(0,3,4));//[4,2,3,4,5]
console.log(A.copyWithin(0,-1,-4));//[4,2,3,4,5]
//5.数组实例的 find() 和 findIndex()
console.log([1,2,-4].find((n)=>n<0))//-4
//6.fill() 方法使用给定值,填充一个数组。
console.log(A.fill(7));//(5) [7, 7, 7, 7, 7]
const B=[1,2,3,4,5]
console.log(B.fill(7,1,2));
//7.ES6 提供三个新的方法—— entries() ,keys() 和 values()——用于遍历数组。它们都返回一个遍历器对象
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}//a b
for (let index of ['a', 'b'].keys()) {
console.log(index);//0 1
} //a b
for(let [index,elem] of ['a','b'].entries()){
console.log(index,elem);
}//0 a 1 b
//8.数组实例的flat(),flatMap() //降维
const C=[1,2,3,[4,5,[6,7]]]
console.log(C.flat());//) [1, 2, 3, 4, 5, Array(2)]
console.log(C.flat(2));//(7) [1, 2, 3, 4, 5, 6, 7]
//如果不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数
console.log(C.flat(Infinity));// [1, 2, 3, 4, 5, 6, 7]
//flatMap()只能开展一层数组,flatMap()方法对原数组的每个成员执行一个函数(相当于执行 Array.prototype.map() ),然后对返回值组成的数组执行 flat() 方法。该方法返回一个新数组,不改变原数组。
const arr5=[1,2,3]
const result=arr5.flatMap(item=>[item*10])
console.log(result);// [10, 20, 30]
//9. Array.prototype.sort() 的排序稳定性
const arr7=['peach','straw','apple','sport']
const stableSorting=(s1,s2)=>{
if (s1[0] < s2[0]) return -1;
return 1;
}
console.log(arr7.sort(stableSorting));//['apple', 'peach', 'straw', 'sport']
</script>
</body>
</html>