有没有办法解构日期?
我知道对于对象你可以做这样的事情。
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
在 ES6 中是否有更好的方法来执行以下操作?是否存在像对象解构这样的东西?
function getFormattedDate(date) {
return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
}
最佳答案
您可以创建一个继承自 Date
对象的对象,添加月、日和年的 getter,然后可以对其进行解构。尽管它有一些开销,但如果您经常使用日期,这可能是值得的。此外,您还可以修复一些问题,例如需要在月份中添加 1。
Although you can add the getters directly to the
Date
object, this is a bad practice. You can more about it in this thread - Why is extending native objects a bad practice?.
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)));
关于javascript - ES6 解构日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206725/