数组的扩展
1.Map 和Generator 函数
//Map结构 使用扩展运算符 rest
let mymap = new Map([
[1,'one'],
['two','小明'],
[3,'three'],
]);
var arr=[...mymap.keys()];//[1,two,3]
var arr=[...mymap.values()];//[one,小明,three]
console.log(arr);
//map 需要有返回值 返回一个新的数组,映射 重新整理数据结果 键值vaule,键名索引 index 每条json对象arr
let arrmap = [
{title:"标题",id:"小明",total:122,result:true},
{title:"标题",id:"小刚",total:122,result:false},
{title:"标题",id:"小红",total:122,result:true}
];
let new_arrmap = arrmap.map((vaule,index,arr)=>{ //重新整理数据
let json={};
json.t=`${vaule.title}`;
json.i=vaule.total+200;
json.r=vaule.result == true && '返回的是真值';
return json;
});
console.log(new_arrmap);
//Generator 函数运行后,返回一个遍历器对象,使用扩展运算符。
const generator = function*(){
yield "小明";
yield 2;
yield 3;
};
console.log([...generator()]);//变量generator是一个 Generator 函数,执行后返回的是一个遍历器对象,对这个遍历器对象执行扩展运算符,就会将内部遍历得到的值,转为一个数组。
2.Array.from()
Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。
//arrayLike变量是一个类似数组的对象,Array.from将它转为真正的数组
let arrayLike = {
0:'a',
1:'b',
2:'c',
length:3
};
let arr1 = [].slice.call(arrayLike);//ES5的写法
console.log(arr1);// [a, b, c]
let arr2 = Array.from(arrayLike);//ES6的写法
console.log(arr2);//[a, b, c]
3.Array.of()
Array.of方法用于将一组值,转换为数组。
Array.of基本上可以用来替代Array()或new Array()。
var arrOf=Array.of(11, 8,6,7,8); //[11, 8, 6, 7, 8]
var arrOf=Array.of(3); // [3]
var arrOf=Array.of(3,2).length;// 1
console.log(arrOf);
//这个方法的主要目的,是弥补数组构造函数Array()的不足。参数个数的不同,会导致Array()的行为有差异。
var array=Array(); // []
var array=Array(3, 11, 8); // [3, 11, 8]
var array=Array(3); // [, , ,]
console.log(array);
4.数组实例的 fill()
fill方法使用给定值,填充一个数组。fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。
var fill = ['a', 'b', 'c'].fill(6)// [6, 6, 6]
var fill = new Array(3).fill(6);// [6, 6, 6]
var fill = ['a', 'b', 'c'].fill(8, 1, 2);//[a, 8, c]
var fill = ['a', 'b', 'c','d','e','f'].fill(8, 1, 5);//[a, 8, 8, 8, 8, f]
console.log(fill);
5.数组实例的keys(),values()和 entries()
keys(),values()和 entries()用于遍历数组。它们都返回一个遍历器对象,可以用for…of循环进行遍历。
唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。
//for循环三种写法
for (let index in ['a', 'b']) { //in 和普通直接遍历数组对象方式 一样(这里就没写了) index只是索引值
console.log(index);//0 1
};
//对键名遍历
for (let index of ['a', 'b'].keys()) { //of index是['a', 'b']里面的对象
console.log(index); //0 1
};
//对键值的遍历
for (let index of ['a', 'b'].values()) { //of index是['a', 'b']里面的对象
console.log(index); //a b
};
//对键值对的遍历
for (let index of ['a', 'b'].entries()) { //of index是['a', 'b']里面的对象
console.log(index);//[0, a] [1, b]
};
6.数组实例的 includes()
Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似。
console.log([1, 2, 3].includes(2) ) // true
console.log([1, 2, 3].includes(4))// false
console.log([1, 2, 'NaN'].includes('NaN') ) // true
7.Array.prototype.sort() 的排序稳定性
排序稳定性(stable sorting)是排序算法的重要属性
指的是排序关键字相同的项目,排序前后的顺序不变。
const sort_arr = [
'ZZT',
'ZAZ',
'AAB',
'CCG'
];
console.log(sort_arr.sort()) //按照首字母进行排序

被折叠的 条评论
为什么被折叠?



