ES6 数组扩展

栏目: JavaScript · 发布时间: 6年前

内容简介:ES6 对原生JS的 数据类型进行了扩展数组扩展ES6对数组的扩展新增了

ES6 对原生JS的 数据类型进行了扩展

数组扩展

ES6对数组的扩展新增了

  1. 扩展运算符 (spread) 为3个点 (…)
console.log( ...[ 1 , 2 , 3 ])  //输出 1 2 3
console.log(1,...[2,3,4],5 )  //输出 1 2 3 4 5

可替代 arrayObject.join( ) 和 arrayObject.toString()方法 更方便的将数组转换成字符串
不过在转换后每个字符中间会有一个空格,可以使用 replace(' ','') 将空格给替换掉 
 
function add(x,y){
    return x + y
}

let number = [ 5 , 10 ]
console.log( add(...number) ) // 输出 15

上面的方法将一个数组变为参数再进行运算

如果数组扩展运算符后面是一个空数组,则不产生任何效果

console.log([...[],1])  // 输出 [1]

如果扩展运算符放在括号中 js 会认为这是函数 ,如果这时不是函数调用,则会报错

console.log((...[1,2])) //输出 Uncaught SyntaxError: Unexpected number
console.log(...[1,2])  //输出 1 2

替代apply方法,由于扩展运算符可以展开数组,所以不需要apply方法将数组转为函数的参数了

原ES5 写法
function a(a,b,c){ 
    console.log(a)
    console.log(b)
    console.log(c)
}

var arr = [1 ,2 ,3]

a.apply(unll,args)  //输出  1 2 3

新方法
function a(a,b,c){
    console.log(a)
    console.log(b)
    console.log(c)
}
var arr = [1 ,2 ,3]
a(...args)  //输出  1 2 3

2. Array.from() 将两类对象转为真正的数组: 类似数组的对象 和 可遍历的对象

var a = {
    '0':'a',
    '1':'c',
    '2':'d',
    length:3 // length很重要,没有 length 将无法遍历
}
console.log(Array.from(a)) // 输出 ["a", "b", "c"]

console.log(Array.from('hello')) //输出 ["h", "e", "l", "l", "o"]

如果对象为真正的数组,则会返回一个一模一样的数组

3.Array.of() 将一组值转换为数组

console.log(Array.of()) //输出 []
console.log(Array.of(1,2,3)) //输出 [1, 2, 3]
console.log(Array.of(3)) //输出 [,,,] 
Array.of() 方法只有在参数不少于2个时才会返回由参数组成的数组

Array.of() 可以用来替代 Array() 或 new Array() 不会存在由于参数不同而导致的重载

4.copyWithin() 在数组内部,将制定位置的成员复制到其他位置,覆盖原有成员,然后返回当前数组,会修改当前数组

Array.prototype.copyWithin(target, start = 0, end = this.length)
    target(必需):从该位置开始替换数据。如果为负值,表示倒数。
    start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数。
    end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。


var a = [1,2,3,4,5]
console.log(a.copyWithin(0,3))  //输出 [4, 5, 3, 4, 5]
上面代码表示  从3号位开始直到结束,复制到从0位开始往后排 

// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4) //输出 [4, 2, 3, 4, 5]

// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1) //输出 [4, 2, 3, 4, 5]

可以代替 先使用arrayObject.slice()获取某个位置的元素再使用 arrayObject.splice()删除指定位置的
元素并将之前获得的元素放入数组的这个操作

5.合并数组 扩展运算符提供了数组合并的新写法

var arr = ['a','b']
var arr2 = ['c','d','e']
console.log([...arr,...arr2]) //输出 ['a','b','c','d','e']

转载时请注明出处及相应链接,本文永久地址:https://blog.yayuanzi.com/25385.html

ES6 数组扩展

ES6 数组扩展 微信打赏

ES6 数组扩展 支付宝打赏

感谢您对作者Miya的打赏,我们会更加努力!    如果您想成为作者,请点我


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pattern Recognition and Machine Learning

Pattern Recognition and Machine Learning

Christopher Bishop / Springer / 2007-10-1 / USD 94.95

The dramatic growth in practical applications for machine learning over the last ten years has been accompanied by many important developments in the underlying algorithms and techniques. For example,......一起来看看 《Pattern Recognition and Machine Learning》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具