ES6语法——数组扩展

数组扩展
数组新增特性
  • Array.from
  • Array.of
  • copyWithin
  • find / findIndex
  • fill
  • entries / keys / values 遍历相关
  • includes
{
	//Array.of
	let arr = Array.of(1,2,4,5,6);
	console.log('arr=', arr)//[1,2,4,5,6]
	let empty = Array.of()
	console.log('empty',empty)//[]
}
{
	//Array.from 把伪数组或集合转化为数组
	let p = document.querySelectorAll('p');//集合
	//元素的集合不是数组,无法使用数组的方法
	let pArr = Array.from(p);//转化成数组
	pArr.forEach(function(item,index){
		console.log(item.textContent)//textContent文本内容的方法
	})
	//传入两个参数,类似map的映射,第二个参数是函数,函数起到map的作用
	//遍历数组每一项,然后返回新的数组
	console.log(Array.from([1,3,5],function(item){return item+2}));//[3,5,7]
}
{
	//fill 填充数组
	//数组全部替换成7
	console.log('fill-7',[1,'a',undefined].fill(7));//[7,7,7]
	//数组按照规定长度进行替换
	//第一个参数:替换成什么
	//第二个参数:从数组哪个位置开始比如 0 ,1 ,2(索引值index)
	//第三个参数:在数组的哪个位置结束 (数组长度length)
	console.log('fill,pos',["a","b","c","d","e"].fill(7,1,3));
	//["a", 7, 7, "d", "e"]
}
{
	//entries / keys / values *遍历相关*
	//只取keys下标值 能兼容
	for(let index of ['1','c','ks'].keys()){
		console.log('keys',index)//打印数组下标
		//0
		//1
		//2
	}
	//只取value值 存在兼容,需要polyfill
	for(let value of ['1','c','ks'].values()){
		console.log('values', value)//打印数组value值
		//'1'
		//'c'
		//'ks'
	}
	//既取index又取value 全兼容
	for(let [index,value] of ['1','c','ks'].entries()){
		console.log('index+values',index,value)//打印index,value
		//0 '1'
		//1 'c'
		//2 'ks'
	}
}
{
	//copyWithin 当前数组内部,把指定位置的成员复制到其他位置上
	//第一个参数:从哪个位置开始替换 0,1,2
	//第二个参数:从哪个位置开始读取 0,1,2
	//第三个参数:从哪个位置截止(不包含该位置) 0,1,2 
	console.log([1,2,3,4,5].copyWithin(0,3,4))//[4,2,3,4,5]
	console.log([1,2,3,4,5].copyWithin(0,3))//[4, 5, 3, 4, 5]
	console.log([1,2,3,4,5].copyWithin(0,2,5))//[3, 4, 5, 4, 5]	
}
{
	//find findIndex 只找第一个符合条件的值
	//判断数组中是否包含某个元素,es5里要么遍历,要么使用underscore工具库 
	//find返回的是第一个值
	console.log([1,2,3,4,5,6].find(function(item){return item > 3}))//4
	console.log([1,2,3,4,5,6].find(function(item){return item > 9}))//undefined
	//findIndex返回的是index下标
	console.log([1,2,3,4,5,6].findIndex(function(item){return item > 3}))//3 
	console.log([1,2,3,4,5,6].findIndex(function(item){return item > 9}))//-1
}
{
	//includes 解决了个NaN非数字的变量 ,功能类似于find findIndex
	//数组中是否包含1,能遍历NaN
	console.log('number',[1,2,NaN].includes(1))//true
	//数组中是否包含NaN,es5中是不能将NaN与NaN做相等运算的,
	console.log('number',[1,2,NaN].includes(NaN))//true	
	
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值