首页 > 其他 > 详细

[ES6] Array -- Destructuring and Rest Parameters && for ..of && Arrat.find()

时间:2016-01-04 06:33:44      阅读:430      评论:0      收藏:0      [点我收藏+]

We can use the destructing and rest parameters at the same time when dealing with Array opration.

 

Example 1:

let [first, ...remainingUsers] = ["Sam", "Tyler", "Brook"];
addActiveUsers(first, remainingUsers);  // "Sam", ["Tyler", "Brook"]

 

Example 2:

function buildTopicInfo(topic){
  let title = `<h1>${topic.title}</h1>`;
  let author = `<small>${topic.author}<small>`;

  return [title, author];
}

let topic = getCurrentTopic();
let [topicTitle, topicAuthor] = buildTopicInfo(topic);

 

Example 4:

let topicId = currentTopic();
let activeUsers = ["Sam", "Tyler", "Brook"];

for( let user of activeUsers ){
  notifyTopicReply(topicId,  user);
}
  • for...of can only apply on the intereable object, like array, but not object
  • 技术分享

 

Example 5:

This code will report an type error, because for ... of can not be used for object.

let topicInfo = { 
  title: "New Features in JS", 
  replies: 19, 
  lastReplyFrom: "Tyler"
};

for(let [k, v] of topicInfo){
  console.log(`${k} - ${v}`);
}

 

Example 6: Array.find()

let recentTopics = [
  { 
    title: "Semi-colons: Good or Bad?",
    isLocked: true 
  },
  { 
    title: "New JavaScript Framework Released", 
    isLocked: true 
  },
  { 
    title: "ES2015 - The Shape of JavaScript to Come", 
    isLocked: false 
  }
];

recentTopics.find( (topic)=> !topic.isLocked)

 

[ES6] Array -- Destructuring and Rest Parameters && for ..of && Arrat.find()

原文:http://www.cnblogs.com/Answer1215/p/5097692.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!