本系列文章經過重新編排和擴充,已出書為ECMAScript關鍵30天。原始文章因當時準備時程緊迫,多少有些許錯誤。為了避免造成讀者的困擾,以及配合書籍的內容規劃,將會陸續更新本系列文章。
本篇文章在 2021/11/2 已更新。
String.prototype.padStart(length,padString)padString預設為 ' ' (空字串)。重複填充到字串的前面,直到到達指定的長度 length後回傳。如果 length 小於原來的字串長度,則回傳原字串。
"One Punch Man".padStart(20); // "       One Punch Man"
"One Punch Man".padStart(23, "-"); // "----------One Punch Man"
String.prototype.padEnd(length,padString)與 padStart 相似,不過填充的位置為字串後方。
"One Punch Man".padEnd(20); // "One Punch Man       "
"One Punch Man".padEnd(23, "-"); // "One Punch Man----------"
以上兩種實體方法,主要目的為讓字串能有組成特定的長度,進行格式化。
在Day7有提到物件的迭代器。除了 Object.keys,在 ES2017 中有再擴充可以使用的方法。
Object.values: 依序將每個屬性的值存到陣列Object.entries: 依序將每個屬性的名稱與值存到陣列 A,再把陣列 A 存到陣列 Bconst object1 = {
  a: "somestring",
  b: 42,
};
Object.keys(object1); // ["a", "b"]
Object.values(object1); // ["somestring", 42]
Object.entries(object1); // [["a", "somestring"], ["b", 42]]
Object.getOwnPropertyDescriptors(target)一次取得物件本身所有的屬性特徵。有關更多屬性特徵的介紹,可以參考ECMAScript關鍵30天。
這個方法的主要目的是搭配Object.defineProperties ,來解決 Object.assign 無法正確複製 get & set 屬性的問題。
const obj1 = {
  set prop(v) {
    console.log(v);
  },
};
const obj2 = {};
Object.assign(obj2, obj1);
Object.getOwnPropertyDescriptor(obj2, "prop");
// {value: undefined, writable: true, enumerable: true, configurable: true}
如果使用 Object.getOwnPropertyDescriptors 的話,則可以取到 set。
Object.defineProperties(obj2, Object.getOwnPropertyDescriptors(obj1));
Object.getOwnPropertyDescriptor(obj2, "prop");
// {get: undefined, enumerable: true, configurable: true, set: ƒ}