📜  Rest 参数 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:01:40.009000             🧑  作者: Mango

代码示例4
//******************************************rest parameter
 const double = (...nums) => {//rest parameter is initialized by using three dots
//The numbers in the array called "result" is passed into the rest parameter. 

  console.log(nums);//each number in the rest parameter is ouput to the console
  return nums.map(num => num*2);//each number in the rest parameter is multiplied by 2 and then stored inside a map
};

const result = double(1,3,5,7,2,4,6,8);//creates a constant,called  "result". It then holds an array of numbers, in this example, and it could be an array of any length. 
//The numbers in parentheses after "double" are passed into the rest parameter also called "double"
console.log(result);//The final result is displayed, with each number having been multiplied by 2





// ************************************spread syntax (arrays)
//The spread syntax is similar to the 'rest parameter', one still uses the three dots to initialize it, but the syntax differs slightly, breaking the array up into its various components
const people = ['shaun', 'ryu', 'chun-li'];
//a good use for the spread array would be when we want to take the elements of one array, and spread them into another array (combine them)
const members = ['mario', 'luigi', ...people];
console.log(members);

//spread syntax (objects)
//again, it is similar to the spread syntax for arrays, but this time it is being applied to objects
const person = { name: 'shaun', age: 30, job: 'net ninja' };
//A NEW OBJECT is created, which copies the OBJECT called 'person' and then ALSO creates and fuses the 'personClone' array into the same object
const personClone = { ...person, location: 'manchester' };
console.log(person, personClone);