ES6数组的keil新增数组功能,还是很强大的好多地方用的到

format_list_numbered
12月 08, 2016
devices other
devices other
在其它设备中阅读本文章
spread operator 单 -& 多用法1. 将数组展开成函数的多个参数传统apply方法function fn(x, y, z) {}var args = [1, 2, 3];fn.apply(null,arg)
ES6-spreadfunction fn(x, y, z){}var args = [1, 2, 3];fn(...args);
而且支持多个数组的展开ES6-spread-plusfunction myFunction(v, w, x, y, z) { }var args = [0, 1];myFunction(-1, ...args, 2, ...[3]);
2. 合并数组传统的合并两个数组要通过数组方法concat、splice、push等方法ES6-spread合并数组var parts = ['shoulder', 'knees'];var lyrics = ['head', ...parts, 'and', 'toes'];
3. 类数组对象转数组arrayLike to arrayvar nodeList = document.querySelectorAll('div');var array = [...nodeList];
4. 数组深拷贝 arr = [1,2] arr2 = arr
arr3 = [...arr]
5. 字符串转数组var str = 'love';var arr5 = [...str];console.log(arr5);//[ 'l', 'o', 'v', 'e' ]
rest operator 多 -& 单const [x,...y] = ['a', 'b', 'c']; // x='a' y=['b','c']
剩余参数(rest parameter)允许长度不确定的实参表示为一个数组。
如果一个函数的最后一个形参是以 … 为前缀的,则在函数被调用时,该形参会成为一个数组,数组中的元素都是传递给该函数的多出来的实参的值。
剩余参数和arguments对象的区别
剩余参数只包含那些没有对应形参的实参,而 arguments 对象包含了传给函数的所有实参。
arguments 对象不是一个真实的数组,而剩余参数是真实的 Array
arguments 对象对象还有一些附加的属性 (比如callee属性)。
arguments模拟剩余数组function fn(a, b) {
var args = [].slice.call(arguments, f.length);
restfunction(a, b, ...args){}
解构赋值 语法是一个Javascript表达式,解构赋值允许你使用类似数组或对象字面量的语法将数组和对象的属性赋给各种变量。
var foo = ["one", "two", "three"];var [one, two, three] =console.log(one); console.log(two); console.log(three);
对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。
var o = {p: 42, q: true};var {p, q} =console.log(p); console.log(q); var {p: foo, q: bar} =console.log(foo); console.log(bar);
var a = 1, b = 2[a, b] = [b, a]
从函数实参对象中提取数据
function userId({id}) { return } var user = {
displayName: "jdoe",
fullName: {
firstName: "John",
lastName: "Doe"
} }; console.log("userId: " + userId(user));
for循环解构
var arr = [{name: 'chris', age: 26}, {name: 'jack',
age: 27}, {name: 'peter',age: 28}];for (let {age, name} of arr) {
console.log(name + ' ' + age);}
字符串解构
const [a, b, c, d, e] = 'hello'; a // "h" b // "e" c // "l" d // "l" e // "o"
从函数返回多个值
function example() {
return {
bar: 2};}let { foo, bar } = example();
函数参数默认值
jQuery.ajax = function (url, {async = true,beforeSend = function () {},cache = true,complete = function () {},crossDomain = false,global = true,}) {};
当…作为函数实参或=号右侧时用作spread运算符
当…作为函数形参或=号左侧时用作rest操作符undefined - 知乎分享删除{&debug&:false,&apiRoot&:&&,&paySDK&:&https:\u002F\u002Fpay.zhihu.com\u002Fapi\u002Fjs&,&wechatConfigAPI&:&\u002Fwechat\u002Fjssdkconfig&,&name&:&production&,&instance&:&pin&,&tokens&:{&X-XSRF-TOKEN&:null,&X-UDID&:null,&Authorization&:&oauth c3cef7c66aa9e6a1e3160e20&}}{&database&:{&Post&:{&641472&:{&isPending&:true}},&User&:{},&Comment&:{},&favlists&:{}},&me&:{},&global&:{&experimentFeatures&:{}},&columns&:{&next&:{}},&columnPosts&:{},&columnSettings&:{&colomnAuthor&:[],&uploadAvatarDetails&:&&,&contributeRequests&:[],&contributeRequestsTotalCount&:0,&inviteAuthor&:&&},&postComments&:{},&postReviewComments&:{&comments&:[],&newComments&:[],&hasMore&:true},&favlistsByUser&:{},&favlistRelations&:{},&draft&:{&titleImage&:&&,&titleImageSize&:{},&isTitleImageFullScreen&:false,&canTitleImageFullScreen&:false,&title&:&&,&titleImageUploading&:false,&error&:&&,&content&:&&,&draftLoading&:false,&updating&:false,&globalLoading&:false,&pendingVideo&:{&resource&:null,&error&:null},&deleteFail&:{&fail&:false},&recommendTopic&:[],&reallyRecommendTopics&:[],&selectedColumn&:0,&videoCovers&:[]},&drafts&:{&draftsList&:[],&next&:{}},&config&:{&userNotBindPhoneTipString&:{}},&recommendPosts&:{&articleRecommendations&:[],&columnRecommendations&:[]},&env&:{&edition&:{&baidu&:false,&yidianzixun&:false,&qqnews&:false},&isAppView&:false,&appViewConfig&:{&content_padding_top&:128,&content_padding_bottom&:56,&content_padding_left&:16,&content_padding_right&:16,&title_font_size&:22,&body_font_size&:16,&is_dark_theme&:false,&can_auto_load_image&:true,&app_info&:&OS=iOS&},&isApp&:false,&trafficSource&:&production&,&userAgent&:{&ua&:&Mozilla\u002F5.0 (compatible, MSIE 11, Windows NT 6.3; Trident\u002F7.0; rv:11.0) like Gecko&,&browser&:{&name&:&IE&,&version&:&11&,&major&:&11&},&engine&:{&name&:&Trident&,&version&:&7.0&},&os&:{&name&:&Windows&,&version&:&8.1&},&device&:{},&cpu&:{}}},&message&:{&newCount&:0},&pushNotification&:{&newCount&:0}}公告:由于博客https升级,原博客引用http链接失效,预览及部分图片效果请查看源代码!
es6中常用的字符串、数组、对象的扩展及应用
2647次浏览
目前前端开发流行框架,react,vue,angular以及微信小程序等等,都是对数据的操作,其实es6中对字符串、数组、对象的扩展,对于我们更简单的操作数据提供了方便。今天主要总结一下我项目中主要用到的es6对这些扩展的应用。当然,es6对函数的扩展及其他应用也很重要,关于这些应用,请关注我后面的文章。
includes方法
在e6字符串和数组中,多了一个includes()方法,这个方法我在项目中经常用到。
有人说includes()方法完全可以用indexOf取代,但是indexOf有几个缺点:
一是不够语义化,它的含义是找到参数值的第一个出现位置,所以要去比较是否不等于-1,表达起来不够直观。
二是,它内部使用严格相等运算符(===)进行判断,这会导致对NaN的误判。
[NaN].indexOf(NaN)
但是includes就可以解决这个问题!
[NaN].includes(NaN)
该方法的几个例子:
[1, 2, 3].includes(2)
[1, 2, 3].includes(4)
[1, 2, NaN].includes(NaN) // true
该方法的第二个参数表示搜索的起始位置,默认为0。如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为-4,但数组长度为3),则会重置为从0开始。
[1, 2, 3].includes(3, 3);
[1, 2, 3].includes(3, -1); // true
数组includes方法和字符串includes方法类似:
let s = 'Hello world!';
s.includes('o') // true
s.includes('Hello', 6) // false
应用-求两个数组的交集和差集
数组a和数组b的交集:
a.filter(v =& b.includes(v))
数组a和数组b的差集:
a.concat(b).filter(v =& !a.includes(v) || !b.includes(v))
字符串 startsWith(), endsWith(),repeat(),padStart(),padEnd()
let haorooms = 'Hello world!';
haorooms.startsWith('Hello') // true
haorooms.endsWith('!') // true
'x'.repeat(3) // &xxx&
'hello'.repeat(2) // &hellohello&
'na'.repeat(0) // &&
'na'.repeat('na') // &&
'na'.repeat('3') // &nanana&
'na'.repeat(2.9) // &nana&
padStart(),padEnd()接受2个参数,一个代表补全的长度,一个代表补全的字符串。
'haorooms.com'.padStart(16, 'www.');//&www.haorooms.com&
'haorooms'.padStart(16, '11') //&haorooms&
'haorooms'.padEnd(12, '.com') //&haorooms.com&
'haorooms'.padEnd(5, '.com') //&haorooms&
数组 entries(),keys() 和 values() 及对象的Object.keys(),Object.values(),Object.entries()
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);
var obj = { foo: 'bar', baz: 42 };
Object.keys(obj) //[&foo&, &baz&]
Object.values(obj) //[bar,42]
Object.entries(obj)//[[&foo&, &baz&],[bar,42]]
类数组转为数组
Array.from()
let haorooms = {
'0': 'a',
'1': 'b',
'2': 'c',
// ES5的写法
var arr1 = [].slice.call(haorooms); // ['a', 'b', 'c']
// ES6的写法
let arr2 = Array.from(haorooms); // ['a', 'b', 'c']
扩展运算符也可以将类数组转为数组
var args = [...arguments];
应用,获取p标签中文本长度大于100的标签
let haorooms = document.querySelectorAll('p');
Array.from(haorooms).filter(p =& {
//等同于[...haorooms].filter
return p.textContent.length & 100;
Array.of()将一组值转为数组
Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1
这个方法的主要目的,是弥补数组构造函数Array()的不足。因为参数个数的不同,会导致Array()的行为有差异。
Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]
数组copyWithin()、find() 和 findIndex() 及fill()
数组实例的copyWithin方法,在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组。也就是说,使用这个方法,会修改当前数组。
Array.prototype.copyWithin(target, start = 0, 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]
[1, 4, -5, 10].find((n) =& n & 0)
//上面代码找出数组中第一个小于 0 的成员。
[1, 5, 10, 15].find(function(value, index, arr) {
return value & 9;
[1, 5, 10, 15].findIndex(function(value, index, arr) {
return value & 9;
fill方法使用给定值,填充一个数组。
['a', 'b', 'c'].fill(7)
// [7, 7, 7]
new Array(3).fill(7)
// [7, 7, 7]
fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
表达式用于定义方法名-vuex中经常用到
let obj = {
['h' + 'ello']() {
return 'hi';
obj.hello() // hi
注意,属性名表达式如果是一个对象,默认情况下会自动将对象转为字符串[object Object],这一点要特别小心。
const keyA = {a: 1};
const keyB = {b: 2};
const myObject = {
[keyA]: 'valueA',
[keyB]: 'valueB'
myObject // Object {[object Object]: &valueB&}
上面代码中,[keyA]和[keyB]得到的都是[object Object],所以[keyB]会把[keyA]覆盖掉,而myObject最后只有一个[object Object]属性。
Object.is()
Object.is就是部署这个算法的新方法。它用来比较两个值是否严格相等,与严格比较运算符(===)的行为基本一致。
Object.is('foo', 'foo')
Object.is({}, {})
不同之处只有两个:一是+0不等于-0,二是NaN等于自身。
+0 === -0 //true
NaN === NaN // false
Object.is(+0, -0) // false
Object.is(NaN, NaN) // true
Object.assign()
关于Object.assign(),我前面文章多次提及,请看:
super 关键字
ES6 又新增了另一个类似的关键字super,指向当前对象的原型对象。
const proto = {
foo: 'hello'
const obj = {
foo: 'world',
return super.
Object.setPrototypeOf(obj, proto);
obj.find() // &hello&
react项目中,经常看到
super(props)
这里 super(props) 之后,能在类里通过 this 访问,是因为在 React.Component 里面把传入的 props 绑定到了 this 上去,于是在 super 之后就可以用 this 访问了。
解构赋值数据交换
以前交换2个值比较简单的做法如下:
a=[b,b=a][0]
es6解构赋值如下:
[a,b]=[b,a]
相关文章:
关键词搜索登录以解锁更多InfoQ新功能
获取更新并接收通知
给您喜爱的内容点赞
关注您喜爱的编辑与同行
966,690 六月 独立访问用户
语言 & 开发
架构 & 设计
文化 & 方法
您目前处于:
深入浅出ES6(二):迭代器和for-of循环
深入浅出ES6(二):迭代器和for-of循环
Jason Orendorff
7&他的粉丝
22&他的粉丝
日. 估计阅读时间:
,将区块链技术的创新和早期落地案例带回您的企业
Author Contacted
语言 & 开发
477 他的粉丝
架构 & 设计
1063 他的粉丝
1 他的粉丝
深入浅出ES6
79 他的粉丝
ECMAScript
0 他的粉丝
JavaScript
69 他的粉丝
2 他的粉丝
237 他的粉丝
相关厂商内容
相关赞助商
告诉我们您的想法
允许的HTML标签: a,b,br,blockquote,i,li,pre,u,ul,p
当有人回复此评论时请E-mail通知我
Re: 1个翻译小错误
Re: 1个翻译小错误
疑惑:请问for of 如何得到索引值
允许的HTML标签: a,b,br,blockquote,i,li,pre,u,ul,p
当有人回复此评论时请E-mail通知我
允许的HTML标签: a,b,br,blockquote,i,li,pre,u,ul,p
当有人回复此评论时请E-mail通知我
赞助商链接
InfoQ每周精要
订阅InfoQ每周精要,加入拥有25万多名资深开发者的庞大技术社区。
架构 & 设计
文化 & 方法
InfoQ.com及所有内容,版权所有 ©
C4Media Inc. InfoQ.com 服务器由 提供, 我们最信赖的ISP伙伴。
极客邦控股(北京)有限公司
找回密码....
InfoQ账号使用的E-mail
关注你最喜爱的话题和作者
快速浏览网站内你所感兴趣话题的精选内容。
内容自由定制
选择想要阅读的主题和喜爱的作者定制自己的新闻源。
设置通知机制以获取内容更新对您而言是否重要
注意:如果要修改您的邮箱,我们将会发送确认邮件到您原来的邮箱。
使用现有的公司名称
修改公司名称为:
公司性质:
使用现有的公司性质
修改公司性质为:
使用现有的公司规模
修改公司规模为:
使用现在的国家
使用现在的省份
Subscribe to our newsletter?
Subscribe to our industry email notices?
通过订阅此邮件,我们可能会根据您以往感兴趣的主题向您发送内容。关于更多详情,请参阅我们的。
我们发现您在使用ad blocker。
我们理解您使用ad blocker的初衷,但为了保证InfoQ能够继续以免费方式为您服务,我们需要您的支持。InfoQ绝不会在未经您许可的情况下将您的数据提供给第三方。我们仅将其用于向读者发送相关广告内容。请您将InfoQ添加至白名单,感谢您的理解与支持。

我要回帖

更多关于 指针数组 的文章

 

随机推荐