[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)
随机推荐
- HTML篇之CSS样式:<button></button>按钮变成超链接<a></a>的样式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 【docker】docker部署spring boot服务,但是docker logs查看容器输出控制台日志,没有日志打印,日志未打印,docker logs不打印容器日志
如题: docker部署spring boot服务,但是docker logs查看容器输出控制台日志,没有日志打印,日志未打印,docker logs不打印容器日志 场景再现: docker部署并启动 ...
- java 线程池 使用实例
在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题: 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统 ...
- asp.net 用JWT来实现token以此取代Session
先说一下为什么要写这一篇博客吧,其实个人有关asp.net 会话管理的了解也就一般,这里写出来主要是请大家帮我分析分析这个思路是否正确.我以前有些有关Session的也整理如下: 你的项目真的需要Se ...
- Android之官方导航栏ActionBar
一.ActionBar概述 ActionBar是android3.0以后新增的组件,主要用于标示应用程序以及用户所处的位置并提供相关操作以及全局的导航功能.下面我们就看看如何使用ActionBar,真 ...
- spring mvc 链接 postgresql
上一篇文章已经分享了搭建springmvc:http://www.cnblogs.com/liqiu/p/4252788.html 这一篇来链接数据库postgresql 1.在pom.xml添加几个 ...
- Ubuntu中安装和配置 Java JDK,并卸载自带OpenJDK(以Ubuntu 14.04为例)
1.下载jdk-7u67-linux-x64.tar.gz 2.用ftp客户端工具filezilla上传到ubuntu的合适文件夹.如果如果不能上传到指定文件夹可能是文件夹权限不足,修改文件夹可执行权 ...
- iOS 测试版系统安装说明(粗略翻译)
我们常常看到在https://developer.apple.com/download/这里会有beta版本的ios系统 或者开发软件 关于beta版本的应用,其实有很大用处,好多人会在正式版没有发布 ...
- Visual Studio开发工具升级注意事项
由于前几年公司开发的系统使用的开发工具版本不统一,现在后期维护升级在开发人员的电脑上要同时安装好几个不同的开发工具, 比如VS2008,VS2010,VS2012,甚至还有用VS2003开发的接口之类 ...
- ListView中的Item点击事件和子控件的冲突或者item点击没有反应的解决的方法
fragment中加入了button和checkbox这些控件.此时这些子控件会将焦点获取到.所以经常当点击item时变化的是子控件.item本身的点击没有响应. 这时候就能够使用descendant ...