ES6 解构日期

hui*_*hui 2 javascript ecmascript-6

有没有办法解构日期?

我知道对于对象你可以做这样的事情。

var o = {p: 42, q: true};
var {p, q} = o;

console.log(p); // 42
console.log(q); // true
Run Code Online (Sandbox Code Playgroud)

在 ES6 中是否有更好的方法来执行以下操作?是否存在像对象解构这样的东西?

function getFormattedDate(date) {
    return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
}
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 5

您可以创建一个继承自的对象Date对象的对象,添加月、日和年的 getter,然后可以对其进行解构。尽管它有一些开销,但如果您经常使用日期,这可能是值得的。此外,您还可以修复一些问题,例如需要在月份中添加 1。

尽管您可以将 getter 直接添加到Date对象中,但这是一个不好的做法。您可以在这个线程中了解更多相关信息 -为什么扩展本机对象是一种不好的做法?

class EDate extends Date {  
  get month() {
    return this.getMonth() + 1;
  }
  
  get day() {
    return this.getDate();
  }
  
  get year() {
    return this.getFullYear();
  }
}

const getFormattedDate = ({ month, day, year }) => `${month}/${day}/${year}`

console.log(getFormattedDate(new EDate()));

// since Date can receive another Date as input, you can do this as well

const date = new Date();

console.log(getFormattedDate(new EDate(date)));
Run Code Online (Sandbox Code Playgroud)