what are those triple dot inside the array? marked it with a comment [duplicate]

不羁岁月 提交于 2019-12-20 07:48:37

问题


I was learning how to web scrap in nodejs and came across this kind of array. What is the meaning?

articles = [               //WHAT IS THIS
    ...articles,
    ...new_articles
];

回答1:


When we see three dots (…) in the code, it's either rest parameters or the spread operator.

Rest parameters: When three dots (…) is at the end of function parameters it will gather the rest of the list of arguments into an array.

spread operator: Expands elements of an array (or all iterables) into places where multiple elements can fit.

yourFunction(arg1, arg2, ...argN) { // used like rest parameter here
  console.log(arg1);
  console.log(arg2);
  console.log(argN);
}

var inputs = ["a", "b", "c", "d", "e", "f"];
yourFunction(...inputs); // used like spread operator here

Another example of the spread-operator:

const array1 = ['item1', 'item2', 'item3'];
const array2 = ['item5', 'item6', 'item7'];

const items = [...array1, 'item4', ...array2];

console.log(items);
// 'item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7'


来源:https://stackoverflow.com/questions/54886728/what-are-those-triple-dot-inside-the-array-marked-it-with-a-comment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!