Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数组的扩展(es6) #5

Open
YoursJoker opened this issue Aug 4, 2020 · 0 comments
Open

数组的扩展(es6) #5

YoursJoker opened this issue Aug 4, 2020 · 0 comments

Comments

@YoursJoker
Copy link
Owner

YoursJoker commented Aug 4, 2020

ES6总结系列之 数组的扩展 篇


1.扩展运算符(...)

①扩展运算符(spread)好比rest参数的逆运算,将一个数组转化为逗号分隔的参数序列,可以想象成去掉中括号[]

console.log(...[1, 2, 3])
// 1 2 3

②扩展运算符后面还可以放置表达式

const arr = [
  ...(x > 0 ? ['a'] : []),
  'b',
];

③可以实现数组深拷贝

const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a2] = a1;

2.Array.from(arr, fn(item,index)) --返回一个新数组

Array.from方法将:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)两类对象转为真正的数组
常见的类数组有argumentsNodeList

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};

// ES5的写法
var arr1 = [].prototype.slice.call(arrayLike); // ['a', 'b', 'c']

// ES6的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。

Array.from(arrayLike, x => x * x);
// 等同于
Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]

3.Array.of(a,b,c) //[a, b, c]

Array.of方法用于将一组转化为数组

Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1

弥补数组构造函数Array()的不足,只有当参数个数不少于 2 个时,Array()才会返回由参数组成的新数组。参数个数只有一个时,实际上是指定数组的长度

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]

rest参数同理:

(function(...args) {}).length // 0

总结要点

扩展运算符 ...

  1. 可以实现数组深拷贝 arr = [1,2,3] arr1 = [...arr];
  2. 扩展运算符内部调用的是数据结构的 Iterator 接口,因此只要具有 Iterator 接口的对象,都可以使用扩展运算符,比如 Map 结构。
  3. Generator 函数运行后,返回一个遍历器对象
  4. 没有 Iterator 接口的对象,使用扩展运算符,将会报错
  5. 扩展运算符后面可加表达式 ...(x > 0 ? ['a'] : [])
  6. 扩展运算符后面如果是一个空字符串,则不产生任何效果.
  7. 只有函数调用时,扩展运算符才可以放在圆括号中,否则会报错.
  8. 如果扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错,

常见的类数组:arguments、NodeList

Array.from(arr, fn(ele,index)) --返回一个新数组

  1. 类数组(具有length属性就行)和可遍历的对象(具有Iterat)转换为数组
  2. 回调函数类似于map(fn(ele,index))
  3. 支持第三个参数:用来绑定map里面的this

Array.of(a,b,c) //[a,b,c]

  1. 将一组值转化为数组
  2. 弥补Array()参数为一个时为指定length的缺陷

  • 个人Github,欢迎star^_^
  • ES6总结系列参考自阮一峰《ECMAScript6入门》

上一篇:ES6总结系列之 函数的扩展 篇
下一篇:ES6总结系列之 Symbol 篇

This was referenced Aug 4, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant