[JS] ECMAScript 6 - Array : compare with c#
扩展运算符(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)
- Map 结构的
数组的空位
一个位置的值等于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#的更多相关文章
- [JS] ECMAScript 6 - Inheritance : compare with c#
这一章,估计是js最操蛋的一部分内容. 现代方法: 简介 Object.getPrototypeOf() super 关键字 类的 prototype 属性和__proto__属性 原生构造函数的继承 ...
- [JS] ECMAScript 6 - Variable : compare with c#
前言 范围包括:ECMAScript 新功能以及对象. 当前的主要目的就是,JS的学习 --> ECMAScript 6 入门 let 命令 js 因为let, i的范围限制在了循环中. var ...
- [JS] ECMAScript 6 - Prototype : compare with c#
开胃菜 prototype 对象 JavaScript 语言的继承则是通过“原型对象”(prototype). function Cat(name, color) { // <----构造函数 ...
- [JS] ECMAScript 6 - Class : compare with c#
Ref: Class 的基本语法 Ref: Class 的基本继承 许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为.目前,有一个提案将这项功能,引入了 ECMAScript. ...
- [JS] ECMAScript 6 - Async : compare with c#
一段引言: Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大. 它由社区最早提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise对 ...
- [JS] ECMAScript 6 - Object : compare with c#
Ref: 对象的扩展 Outline: 属性的简洁表示法 属性名表达式 方法的 name 属性 Object.is() Object.assign() 属性的可枚举性和遍历 Object.getOwn ...
- 观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 ...
- js中的Array
js中的Array 啥是ArrayLike对象 类似,下面这种对象的就是ArrayLike var arraylike = { 0: "a", 1: "b", ...
- JS arguments转array
JS arguments转array? Array.prototype.slice.call(arguments)
随机推荐
- ArcGIS教程:曲率
摘要 计算栅格表面的曲率,包括剖面曲率和平面曲率. 用法 · 主要输出结果为每个像元的表面曲率,该值通过将该像元与八个相邻像元拟合而得.曲率是表面的二阶导数,或者可称之为坡度的坡度.可供选择的输出曲率 ...
- scrollView 刷新显示在中间的问题
scrollView问题 打开activity之后 屏幕初始位置不是顶部 而是在中间 也就是scroll滚动条不在上面 而是在中间 楼主你好,我大概是和你遇见了同样的问题,你可以灵活处理一下,不要去管 ...
- IntelliJ IDEA2018.1、2017.3破解教程
(1)下载破解补丁 把下载的破解补丁放在你的idea的安装目录下的bin的目录下面(如下图所示),本文示例为G:\idea\IntelliJ IDEA 2017.3.4 破解补丁下载:http://i ...
- Window Server 2008 R2系统备份
1.安装Backup 2.打开Backup工具 3.一次性备份 下一步
- 6、Python变量
Python变量 变量的定义 变量是计算机内存中的一块区域,变量可以存储规定范围内的值,而且值可以改变. 变量的命名 变量名有字母.数字.下划线组成. 数字不能开头 不可以使用关键字 a a1 a_ ...
- 卡尔曼滤波(Kalman Filter) ZZ
一.引言 以下我们引用文献[1]中的一段话作为本文的開始: 想象你在黄昏时分看着一仅仅小鸟飞行穿过浓密的丛林.你仅仅能隐隐约约.断断续续地瞥见小鸟运动的闪现.你试图努力地猜測小鸟在哪里以及下一时刻它会 ...
- VMware相关服务启动关闭脚本
VMware相关服务 VMware Authonrization Service:用于启动和访问虚拟机的授权和身份验证服务 VMware DHCP Service: IP自动分配协议——它不启动 虚拟 ...
- windows多线程同步--互斥量
关于互斥量的基本概念:百度百科互斥量 推荐参考博客:秒杀多线程第七篇 经典线程同步 互斥量Mutex 注意:互斥量也是一个内核对象,它用来确保一个线程独占一个资源的访问.互斥量与关键段的行为非常相似, ...
- 基于Centos搭建 Hadoop 伪分布式环境
软硬件环境: CentOS 7.2 64 位, OpenJDK- 1.8,Hadoop- 2.7 关于本教程的说明 云实验室云主机自动使用 root 账户登录系统,因此本教程中所有的操作都是以 roo ...
- 编写SHELL脚本--判断用户的参数
测试语句格式: [ 条件表达式 ] 常见的几种形式: [ -d /etc ] 判断/etc是不是一个目录类型, [ -e /etc/php.ini ] 判断/etc/php.ini 文件是否存在 [ ...