扩展运算符(spread)

先复习下 rest 参数。

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

// https://blog.csdn.net/weixin_39723544/article/details/78460470

function foo(a, b) {
var i, rest = [];
if (arguments.length > 2) {
for (i = 2; i<arguments.length; i++) {
rest.push(arguments[i]);
}
}
console.log('a = ' + a);
console.log('b = ' + b);
console.log(rest);
}

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

function foo(a, b, ...rest) {
console.log('a = ' + a);
console.log('b = ' + b);
console.log(rest);
} foo(1, 2, 3, 4, 5);
// 结果:
// a = 1
// b = 2
// Array [ 3, 4, 5 ] foo(1);
// 结果:
// a = 1
// b = undefined
// Array []

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

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

function push(array, ...items) {
array.push(...items);
} function add(x, y) {
return x + y;
} const numbers = [4, 38];
add(...numbers) //

- 参数,任意位置

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

-  表达式,先计算出结果

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

- 空,则无效

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

替代函数的 apply 方法

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

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

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

function add(j, k){
return j+k;
} function sub(j, k){
return j-k;
}

我们在控制台运行:

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

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

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

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

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

扩展运算符的应用

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

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

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

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

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

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

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

------------------------------------------------------
// (2) arguments对象
function foo() {
var args = Array.from(arguments);
// ...
}

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

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

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

* 接受第二个参数,作用类似于数组的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]

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

let spans  = document.querySelectorAll('span.name');

// map()
let names1 = Array.prototype.map.call(spans, s => s.textContent); // Array.from()
let names2 = Array.from(spans, s => s.textContent)  // <---- 看上去简洁

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

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

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

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

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

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

Array.of()

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

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

现在的方法:

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

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

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

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

copyWithin()


/**
* Array.prototype.copyWithin(target, start = , end = this.length)
**/
// 将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] // 将3号位复制到0号位
[].copyWithin.call({length: 5, 3: 1}, 0, 3)
// {0: 1, 3: 1, length: 5} // 将2号位到数组结束,复制到0号位
let i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5] // 对于没有部署 TypedArray 的 copyWithin 方法的平台
// 需要采用下面的写法
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]

find() 和 findIndex()

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

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

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

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

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

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

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

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

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

NaN是什么东东?

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

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

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

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

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

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

(2) 元素索引

(3) 原数组本身

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

fill()

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

entries(),keys() 和 values()

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

  • for...of循环
for (let index of ['a', 'b'].keys()) {  // 对键名的遍历
console.log(index);
}
//
// for (let elem of ['a', 'b'].values()) {  // 对键值的遍历
console.log(elem);
}
// 'a'
// 'b' for (let [index, elem] of ['a', 'b'].entries()) {  // 对键值对的遍历
console.log(index, elem);
}
// 0 "a"
// 1 "b"
  • next方法

includes()

是否包含该元素。

[1, 2, NaN].includes(NaN) // true
[NaN].indexOf(NaN)
// -1  导致了误判 [1, 2, 3].includes(3, 3); // false
[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

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

Array.from(['a',,'b'])
// [ "a", undefined, "b" ] [...['a',,'b']]
// [ "a", undefined, "b" ] [,'a','b',,].copyWithin(2,0) // [,"a",,"a"] new Array(3).fill('a') // ["a","a","a"] let arr = [, ,];
for (let i of arr) {
console.log(1);
}
//
// 1
// entries()
[...[,'a'].entries()] // [[0,undefined], [1,"a"]] // keys()
[...[,'a'].keys()] // [0,1] // values()
[...[,'a'].values()] // [undefined,"a"] // find()
[,'a'].find(x => true) // undefined // findIndex()
[,'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. 获取域名,url,指定url参数的方法

    1.js获取域名的方法 1) var domain = document.domain 2) var domain = window.location.host 2.获取url的方法 1) var u ...

  2. sitemap xml文件生成

    sitemap xml生成方法 <?php /** * SitemapService.php. * * 生成sitemap */ class Sitemap { public $newLine ...

  3. Introduction to pinatrace annotate version 2: a look into latches again

    https://fritshoogland.wordpress.com/2017/12/22/introduction-to-pinatrace-annotate-version-2-a-look-i ...

  4. EasyUI学习总结(二)——easyloader分析与使用(转载)

    本文转载自:http://www.cnblogs.com/haogj/archive/2013/04/22/3036685.html 使用脚本库总要加载一大堆的样式表和脚本文件,在easyui 中,除 ...

  5. ToolTip C#

    yourToolTip = new ToolTip(); //The below are optional, of course, yourToolTip.ToolTipIcon = ToolTipI ...

  6. 1.2 Stream API

    引例: List<String> strList = Arrays.asList("zhaojigang","nana","tianya& ...

  7. android-activity生命周期方法

    整个Activity生命周期中的所有方法,我们可以根据程序的需要来覆盖相应的方法: public class Activity extends ApplicationContext { //创建的时候 ...

  8. Spark2.3(三十七):Stream join Stream(res文件每天更新一份)

    kafka测试数据生成: package com.dx.kafka; import java.util.Properties; import java.util.Random; import org. ...

  9. Centos或Windows中部署Zookeeper集群及其简单用法

    一.简介 ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件.它是一个为分布式应用提供一致性服务的软件 ...

  10. php 实现发送微信模板消息(转)

    <?php namespace Org\Weixin; /** * Created by PhpStorm. * User: StandOpen * Date: 15-1-7 * Time: 9 ...