zoukankan      html  css  js  c++  java
  • [ES6] Array -- Destructuring and Rest Parameters && for ..of && Arrat.find()

    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)
  • 相关阅读:
    L7-1 文本处理
    L6-14 继承多态
    L6-13 魔法方法
    L6-12 类的实例
    L6-11 综合运用
    L6-2 嵌套循环
    golang 关于引用类型
    golang close for channel
    go tip
    vscode官方文档
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5097692.html
Copyright © 2011-2022 走看看