扩展运算符(spread)

先复习下 rest 参数。

(1) argument模式,但不够好。

  1. // https://blog.csdn.net/weixin_39723544/article/details/78460470
  2.  
  3. function foo(a, b) {
  4. var i, rest = [];
  5. if (arguments.length > 2) {
  6. for (i = 2; i<arguments.length; i++) {
  7. rest.push(arguments[i]);
  8. }
  9. }
  10. console.log('a = ' + a);
  11. console.log('b = ' + b);
  12. console.log(rest);
  13. }

(2) 更灵活,但需要在尾部,且不能给默认参数。

  1. function foo(a, b, ...rest) {
  2. console.log('a = ' + a);
  3. console.log('b = ' + b);
  4. console.log(rest);
  5. }
  6.  
  7. foo(1, 2, 3, 4, 5);
  8. // 结果:
  9. // a = 1
  10. // b = 2
  11. // Array [ 3, 4, 5 ]
  12.  
  13. foo(1);
  14. // 结果:
  15. // a = 1
  16. // b = undefined
  17. // Array []

(3) 三个点(...),它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。

该运算符主要用于函数调用,尤其是,数组作为参数时。

  1. function push(array, ...items) {
  2. array.push(...items);
  3. }
  4.  
  5. function add(x, y) {
  6. return x + y;
  7. }
  8.  
  9. const numbers = [4, 38];
  10. add(...numbers) //

- 参数,任意位置

  1. function f(v, w, x, y, z) { }
  2. const args = [0, 1];
  3. f(-1, ...args, 2, ...[3]);

-  表达式,先计算出结果

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

- 空,则无效

  1. [...[], 1]
  2. // [1]

替代函数的 apply 方法

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

  • apply干嘛的? 
  1. obj.call(thisObj, arg1, arg2, ...);
  2. obj.apply(thisObj, [arg1, arg2, ...]);

唯一区别是apply接受的是数组参数,call接受的是连续参数。

  1. function add(j, k){
  2. return j+k;
  3. }
  4.  
  5. function sub(j, k){
  6. return j-k;
  7. }

我们在控制台运行:

  1. add(5,3); //
  2. add.call(sub, 5, 3); //
  3. add.apply(sub, [5, 3]); //
  4.  
  5. sub(5, 3); //
  6. sub.call(add, 5, 3); //
  7. sub.apply(add, [5, 3]); //
  • 不再需要apply方法!

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

  1. // ES5 的写法
  2. Math.max.apply(null, [14, 3, 77])
  3.  
  4. // ES6 的写法
  5. Math.max(...[14, 3, 77])  // 看上去比apply舒服一些
  6.  
  7. // 等同于
  8. Math.max(14, 3, 77);

挽救apply的参数格式之鸡肋。

  1. // ES5的 写法
  2. var arr1 = [0, 1, 2];
  3. var arr2 = [3, 4, 5];
  4. Array.prototype.push.apply(arr1, arr2);  // 因为push的参数格式要求是个鸡肋
  5.  
  6. // ES6 的写法
  7. let arr1 = [0, 1, 2];
  8. let arr2 = [3, 4, 5];
  9. arr1.push(...arr2);    // <---- 看着舒服多了

扩展运算符的应用

  • 浅复制
  1. const a1 = [1, 2];
  2. const a2 = a1;
  • 扩展运算符 - 深拷贝
  1. const a1 = [1, 2];
  2. // 写法一
  3. const a2 = [...a1];  //
  4. // 写法二
  5. const [...a2] = a1;
  • 扩展运算符 - 合并
  1. // ES5的合并数组
  2. arr1.concat(arr2, arr3);
  3. // [ 'a', 'b', 'c', 'd', 'e' ]
  4.  
  5. // ES6的合并数组
  6. [...arr1, ...arr2, ...arr3]
  7. // [ 'a', 'b', 'c', 'd', 'e' ]
  • 扩展运算符 - 与解构赋值结合
  1. const [first, ...rest] = [1, 2, 3, 4, 5];
  2. first //
  3. rest // [2, 3, 4, 5]
  4.  
  5. const [first, ...rest] = [];
  6. first // undefined
  7. rest // []
  8.  
  9. const [first, ...rest] = ["foo"];
  10. first // "foo"
  11. rest // []
  • 扩展运算符 - 字符串
  1. [...'hello']
  2. // [ "h", "e", "l", "l", "o" ]

* 只要是部署了 Iterator 接口的数据结构,Array.from都能将其转为数组。

  1. Array.from('hello')
  2. // ['h', 'e', 'l', 'l', 'o']
  3.  
  4. let namesSet = new Set(['a', 'b'])
  5. Array.from(namesSet) // ['a', 'b']
  • 扩展运算符 - 类数组“转正”
  1. let nodeList = document.querySelectorAll('div');  // nodList类数组,可能其中没有直接使用数组的很多方法
  2. let array = [...nodeList];
  • 扩展运算符 - 具备Iterator 接口的对象【如果对没有 Iterator 接口的对象,使用扩展运算符,将会报错】
  1. let map = new Map([
  2. [1, 'one'],
  3. [2, 'two'],
  4. [3, 'three'],
  5. ]);
  6.  
  7. let arr = [...map.keys()]; // [1, 2, 3]
  8.  
  9. ------------------------------------------------------
  10.  
  11. // 1. 变量go是一个 Generator 函数,执行后返回的是一个遍历器对象,
  1. const go = function*(){  
  2. yield 1;
  3. yield 2;
  4. yield 3;
  5. };
  6. [...go()]    // 2. 对这个遍历器对象执行扩展运算符, 就会将内部遍历得到的值,转为一个数组。
    // [1, 2, 3]

* 只要是部署了 Iterator 接口的数据结构,Array.from都能将其转为数组。

  1. let namesSet = new Set(['a', 'b'])
  2. Array.from(namesSet) // ['a', 'b']
  • 扩展运算符 - 类似数组的对象 【Array.from】
  1. let arrayLike = {
  2. '0': 'a',
  3. '1': 'b',
  4. '2': 'c',
  5. length: 3
  6. };
  7.  
  8. // ES5的写法
  9. var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']
  10.  
  11. // ES6的写法
  12. let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

* 实际应用中,常见的类似数组的对象是:

  1. // (1) NodeList对象
  2. let ps = document.querySelectorAll('p');
  3. Array.from(ps).filter(p => {
  4. return p.textContent.length > 100;
  5. });

  6. ------------------------------------------------------
  7. // (2) arguments对象
  8. function foo() {
  9. var args = Array.from(arguments);
  10. // ...
  11. }

本质特征只有一点,任何有length属性的对象,都可以通过Array.from方法转为数组,而此时扩展运算符就无法转换。比如:

  1. Array.from({ length: 3 });
  2. // [ undefined, undefined, undefined ]

对于还没有部署该方法的浏览器,可以用Array.prototype.slice方法替代。  

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

  1. Array.from(arrayLike, x => x * x);
  2. // 等同于
  3. Array.from(arrayLike).map(x => x * x);
  4.  
  5. Array.from([1, 2, 3], (x) => x * x)
  6. // [1, 4, 9]

取出一组 DOM 节点的文本内容

  1. let spans = document.querySelectorAll('span.name');
  2.  
  3. // map()
  4. let names1 = Array.prototype.map.call(spans, s => s.textContent);
  5.  
  6. // Array.from()
  7. let names2 = Array.from(spans, s => s.textContent)  // <---- 看上去简洁

例1: 将数组中布尔值为false的成员转为0

  1. Array.from([1, , 2, , 3], (n) => n || 0)
  2. // [1, 0, 2, 0, 3] 

例2: 返回各种数据的类型。

  1. function typesOf () {
  2. return Array.from(arguments, value => typeof value)
  3. }
  4. typesOf(null, [], NaN)
  5. // ['object', 'object', 'number']

例3: 返回字符串(Unicode 字符)的长度。

  1. function countSymbols(string) {
  2. return Array.from(string).length;
  3. }

Array.of()

原来的方式:表达比较混乱。

  1. Array() // []
  2. Array(3) // [, , ,]
  3. Array(3, 11, 8) // [3, 11, 8]  这里又变成了数组的内容?!

现在的方法:

Array.of基本上可以用来替代Array()new Array()。

Array.of总是返回参数值组成的数组。如果没有参数,就返回一个空数组。

Array.of方法可以用下面的代码模拟实现。

  1. function ArrayOf(){
  2. return [].slice.call(arguments);
  3. }

copyWithin()

  1.  
  1. /**
    * Array.prototype.copyWithin(target, start = , end = this.length)
    **/
  1. // 将3号位复制到0号位
  2. [1, 2, 3, 4, 5].copyWithin(0, 3, 4)
  3. // [4, 2, 3, 4, 5]
  4.  
  5. // -2相当于3号位,-1相当于4号位
  6. [1, 2, 3, 4, 5].copyWithin(0, -2, -1)
  7. // [4, 2, 3, 4, 5]
  8.  
  9. // 将3号位复制到0号位
  10. [].copyWithin.call({length: 5, 3: 1}, 0, 3)
  11. // {0: 1, 3: 1, length: 5}
  12.  
  13. // 将2号位到数组结束,复制到0号位
  14. let i32a = new Int32Array([1, 2, 3, 4, 5]);
  15. i32a.copyWithin(0, 2);
  16. // Int32Array [3, 4, 5, 4, 5]
  17.  
  18. // 对于没有部署 TypedArray 的 copyWithin 方法的平台
  19. // 需要采用下面的写法
  20. [].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
  21. // Int32Array [4, 2, 3, 4, 5]

find() 和 findIndex()

基础:第一个返回值为true的成员

  1. [1, 4, -5, 10].find((n) => n < 0)
  2. // -5

高级:参数更多,灵活性更强,比如比较相邻的元素。

  1. [1, 5, 10, 15].find(function(value, index, arr) {
  2. return value > 9;
  3. }) // 

第二参数:引入另一个对象

  1. function f(v){
  2. return v > this.age;
  3. }
  4. let person = {name: 'John', age: 20};
  5.  
  6. /* person 对应上述f(v)函数中的this */
  7. [10, 12, 26, 15].find(f, person); //

补丁:数组的indexOf方法的不足,无法识别数组的NaN成员。

  1. [NaN].indexOf(NaN)
  2. // -1

  3. // findIndex方法可以借助Object.is方法做到。
  4. [NaN].findIndex(y => Object.is(NaN, y))
  5. //

NaN是什么东东?

NaN: Not a Number。代表非数字值的特殊值。该属性用于指示某个值不是数字。可以把 Number 对象设置为该值,来指示其不是数字值。

提示:请使用 isNaN() 全局函数来判断一个值是否是 NaN 值。

方法 parseInt() 和 parseFloat() 在不能解析指定的字符串时就返回这个值。

对于一些常规情况下返回有效数字的函数,也可以采用这种方法,用 Number.NaN 说明它的错误情况。

map方法在调用callback函数时,会自动给它传递三个参数:

(1) 当前正在遍历的元素

(2) 元素索引

(3) 原数组本身

第三个参数parseInt会忽视, 但第二个参数不会,也就是说,parseInt把传过来的索引值当成进制数来使用,从而返回了NaN。

fill()

  1. // 抹去式填充
  2. ['a', 'b', 'c'].fill(7)
  3. // [7, 7, 7]
  4.  
  5. new Array(3).fill(7)
  6. // [7, 7, 7]
  7.  
  8. // 或者自定义位置抹去
  9. ['a', 'b', 'c'].fill(7, 1, 2)
  10. // ['a', 7, 'c']

entries(),keys() 和 values()

ES6 提供三个新的方法,遍历数组。

  • for...of循环
  1. for (let index of ['a', 'b'].keys()) {  // 对键名的遍历
  2. console.log(index);
  3. }
  4. //
  5. //
  6.  
  7. for (let elem of ['a', 'b'].values()) {  // 对键值的遍历
  8. console.log(elem);
  9. }
  10. // 'a'
  11. // 'b'
  12.  
  13. for (let [index, elem] of ['a', 'b'].entries()) {  // 对键值对的遍历
  14. console.log(index, elem);
  15. }
  16. // 0 "a"
  17. // 1 "b"
  • next方法

includes()

是否包含该元素。

  1. [1, 2, NaN].includes(NaN) // true
  2. [NaN].indexOf(NaN)
  3. // -1  导致了误判
  4.  
  5. [1, 2, 3].includes(3, 3); // false
  6. [1, 2, 3].includes(3, -1); // true

另外,Map 和 Set 数据结构有一个has方法,需要注意与includes区分。

    • Map 结构的has方法,是用来查找键名的,比如:

      • Map.prototype.has(key)
      • WeakMap.prototype.has(key)
      • Reflect.has(target, propertyKey)
    • Set 结构的has方法,是用来查找值的,比如:
      • Set.prototype.has(value)
      • WeakSet.prototype.has(value)

数组的空位

一个位置的值等于undefined,依然是有值的。

空位是没有任何值。如下:

第一个数组的 0 号位置是有值的;第二个数组的 0 号位置没有值。

ES5 对空位的处理,已经很不一致了,大多数情况下会忽略空位。

ES6 则是明确将空位转为undefined

”由于空位的处理规则非常不统一,所以建议避免出现空位。“

  1. Array.from(['a',,'b'])
  2. // [ "a", undefined, "b" ]
  3.  
  4. [...['a',,'b']]
  5. // [ "a", undefined, "b" ]
  6.  
  7. [,'a','b',,].copyWithin(2,0) // [,"a",,"a"]
  8.  
  9. new Array(3).fill('a') // ["a","a","a"]
  10.  
  11. let arr = [, ,];
  12. for (let i of arr) {
  13. console.log(1);
  14. }
  15. //
  16. // 1
  1. // entries()
  2. [...[,'a'].entries()] // [[0,undefined], [1,"a"]]
  3. // keys()
  4. [...[,'a'].keys()] // [0,1]
  5. // values()
  6. [...[,'a'].values()] // [undefined,"a"]
  7. // find()
  8. [,'a'].find(x => true) // undefined
  9. // findIndex()
  10. [,'a'].findIndex(x => true) // 0
 

[JS] ECMAScript 6 - Array : compare with c#的更多相关文章

  1. [JS] ECMAScript 6 - Inheritance : compare with c#

    这一章,估计是js最操蛋的一部分内容. 现代方法: 简介 Object.getPrototypeOf() super 关键字 类的 prototype 属性和__proto__属性 原生构造函数的继承 ...

  2. [JS] ECMAScript 6 - Variable : compare with c#

    前言 范围包括:ECMAScript 新功能以及对象. 当前的主要目的就是,JS的学习 --> ECMAScript 6 入门 let 命令 js 因为let, i的范围限制在了循环中. var ...

  3. [JS] ECMAScript 6 - Prototype : compare with c#

    开胃菜 prototype 对象 JavaScript 语言的继承则是通过“原型对象”(prototype). function Cat(name, color) { // <----构造函数 ...

  4. [JS] ECMAScript 6 - Class : compare with c#

    Ref: Class 的基本语法 Ref: Class 的基本继承 许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为.目前,有一个提案将这项功能,引入了 ECMAScript. ...

  5. [JS] ECMAScript 6 - Async : compare with c#

    一段引言: Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大. 它由社区最早提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise对 ...

  6. [JS] ECMAScript 6 - Object : compare with c#

    Ref: 对象的扩展 Outline: 属性的简洁表示法 属性名表达式 方法的 name 属性 Object.is() Object.assign() 属性的可枚举性和遍历 Object.getOwn ...

  7. 观V8源码中的array.js,解析 Array.prototype.slice为什么能将类数组对象转为真正的数组?

    在官方的解释中,如[mdn] The slice() method returns a shallow copy of a portion of an array into a new array o ...

  8. js中的Array

    js中的Array 啥是ArrayLike对象 类似,下面这种对象的就是ArrayLike var arraylike = { 0: "a", 1: "b", ...

  9. JS arguments转array

    JS arguments转array? Array.prototype.slice.call(arguments)

随机推荐

  1. ArcGIS教程:曲率

    摘要 计算栅格表面的曲率,包括剖面曲率和平面曲率. 用法 · 主要输出结果为每个像元的表面曲率,该值通过将该像元与八个相邻像元拟合而得.曲率是表面的二阶导数,或者可称之为坡度的坡度.可供选择的输出曲率 ...

  2. scrollView 刷新显示在中间的问题

    scrollView问题 打开activity之后 屏幕初始位置不是顶部 而是在中间 也就是scroll滚动条不在上面 而是在中间 楼主你好,我大概是和你遇见了同样的问题,你可以灵活处理一下,不要去管 ...

  3. IntelliJ IDEA2018.1、2017.3破解教程

    (1)下载破解补丁 把下载的破解补丁放在你的idea的安装目录下的bin的目录下面(如下图所示),本文示例为G:\idea\IntelliJ IDEA 2017.3.4 破解补丁下载:http://i ...

  4. Window Server 2008 R2系统备份

    1.安装Backup 2.打开Backup工具 3.一次性备份 下一步

  5. 6、Python变量

    Python变量 变量的定义 变量是计算机内存中的一块区域,变量可以存储规定范围内的值,而且值可以改变. 变量的命名 变量名有字母.数字.下划线组成. 数字不能开头 不可以使用关键字 a a1 a_ ...

  6. 卡尔曼滤波(Kalman Filter) ZZ

    一.引言 以下我们引用文献[1]中的一段话作为本文的開始: 想象你在黄昏时分看着一仅仅小鸟飞行穿过浓密的丛林.你仅仅能隐隐约约.断断续续地瞥见小鸟运动的闪现.你试图努力地猜測小鸟在哪里以及下一时刻它会 ...

  7. VMware相关服务启动关闭脚本

    VMware相关服务 VMware Authonrization Service:用于启动和访问虚拟机的授权和身份验证服务 VMware DHCP Service: IP自动分配协议——它不启动 虚拟 ...

  8. windows多线程同步--互斥量

    关于互斥量的基本概念:百度百科互斥量 推荐参考博客:秒杀多线程第七篇 经典线程同步 互斥量Mutex 注意:互斥量也是一个内核对象,它用来确保一个线程独占一个资源的访问.互斥量与关键段的行为非常相似, ...

  9. 基于Centos搭建 Hadoop 伪分布式环境

    软硬件环境: CentOS 7.2 64 位, OpenJDK- 1.8,Hadoop- 2.7 关于本教程的说明 云实验室云主机自动使用 root 账户登录系统,因此本教程中所有的操作都是以 roo ...

  10. 编写SHELL脚本--判断用户的参数

    测试语句格式: [ 条件表达式 ] 常见的几种形式: [ -d /etc ]  判断/etc是不是一个目录类型, [ -e /etc/php.ini ] 判断/etc/php.ini 文件是否存在 [ ...