特別提出這兩個方法,是因為在上課時,聽到這兩個方法是現在Obj & Array 最好用的方法,故特別提出
DefineProperties(For Obj)
let obj = {};
Object.defineProperties(obj, {
property1: {
value: 1,
writable: true,
},
property2: {
value: 'Hello',
writable: false,
},
// etc. etc.
});
console.log(obj.property1); //1
console.log(obj.property2); //Hello
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false
});
//writable:false,不可被覆寫
object1.property1 = 77;
// throws an error in strict mode
console.log(object1.property1);
// expected output: 42
DefineProperties Combine Demo
let a = {
name: "Liu",
age: 30
};
Object.defineProperties(a, {
name: {
writable: false
},
age2: {
enumerable: true,
get() {
console.log("get age");
return this.age;
},
set(val) {
console.log("set age");
this.age = val;
}
}
});
a.name = "XXX";
a.age2 = 35;
console.log(a);
//console.log 呼叫a
//a去defineProperties裡面找
//用function 可以拿到額外通知
//輸出{ name: 'Liu', age: 35, age2: [Getter/Setter] }
arr.reduce(
callback
(accumulator, currentValue[, index[, array]])
[, initialValue]
)
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
// reducer是要執行的函式
// 「5」是初始值
//Do Sum
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
//初始值設定為0
var total = [ 0, 1, 2, 3 ].reduce(
( acc, cur ) => acc + cur, 5
);
//初始值設定為5
var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(
(accumulator, currentValue) => accumulator + currentValue.x
,initialValue
);
console.log(sum) // 6