[ES6] Rest Parameter

Problem with the ES5:

function displayTags(){
    for (let i in arguments) {
        let tag = arguments[i];
        _addToTopic(tag);
    }
}
  • Hard to tell which parameters this functon expects to be called with
  • arguments -- where did this come from?
  • IF we add an agument, it will break everything:
function displayTags(targetElement){

    let target = _findElement(targetElement);

    for (let i in arguments) {
        let tag = arguments[i]; // break the loop, since the first arguments is no longer a tag
        _addToTopic(target, tag);
    }
}

 

 

Improvement from ES6:

// Cannot assign default value to Rest Parameter
// Rest Parameter should alwasys come at the last
const displayTags = (blogName="New Blog", ...tags) => {
  console.log(blogName, tags);
}

displayTags("ES2015", "Javascript", "ES6", "Babel");

 

posted @ 2016-01-02 21:47  Zhentiw  阅读(264)  评论(0)    收藏  举报