Discuss / JavaScript / 结构函数与rest结合的写法,值得研究下

结构函数与rest结合的写法,值得研究下

Topic source

雏鹰

#1 Created at ... [Delete] [Delete and Lock User]
//  !!! 如果一个函数接收一个对象作为参数,那么,可以使用解构直接把对象的属性绑定到变量中。
function buildDate({ year, month, day, hour = 0, minute = 0, second = 0 }) {
  console.log(arguments); // ! [Arguments] { '0': { year: 2022, month: 12, day: 27 } }
  console.log(arguments[0]); // ! { year: 2022, month: 12, day: 27 }
  return new Date(
    year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
  );
}
console.log(buildDate({ year: 2022, month: 12, day: 27 }));

function buildDate(...rest) {
  console.log(arguments); // ! [Arguments] { '0': { year: 2022, month: 12, day: 27 } }
  console.log(arguments.length); // ! [Arguments] { '0': { year: 2022, month: 12, day: 27 } }
  console.log(arguments[0]); // ! { year: 2022, month: 12, day: 27 }
  console.log(rest); // ! [ { year: 2022, month: 12, day: 27 } ]

  // !!! 很神奇的存在
  if (arguments.length) {
    arg = arguments[0];
  } else {
    arg = arguments;
  }

  // ! 默认的赋值
  var {
    year = 1981,
    month = 1,
    day = 1,
    hour = 0,
    minute = 0,
    second = 0,
  } = arg;

  return new Date(
    year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second
  );
}
console.log(buildDate({ year: 2022, month: 12, day: 27 }));
console.log(buildDate());
console.log(buildDate({}));
var obj = {x: 1, y: 2, z: 3};
var {a=4, b=5, c=6} = obj;
(function foo(...rest) {alert(rest)})(a, b, c); // 4 5 6

  • 1

Reply