Easy
Create a class ArrayWrapper
that accepts an array of integers in its constructor. This class should have two features:
+
operator, the resulting value is the sum of all the elements in both arrays.String()
function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3]
.建立一個類別ArrayWrapper
,在其建構函式中接受整數陣列。 這個類別應該有兩個特點:
+
運算子將此類別的兩個實例相加時,結果值是兩個陣列中所有元素的總和。String()
函數時,將傳回一個用括號括起來的逗號分隔字串。 例如,[1,2,3]
。class ArrayWrapper {
constructor(nums) {
this.nums = nums;
}
//使用Array.flat(1); 將多維陣列平坦化為一維陣列
//使用Array.reduce(); 相加所有元素
valueOf() {
const flattenArray = this.nums.flat(1);
return flattenArray.reduce((sum, num) => sum + num, 0);
}
//使用Array.join(,) 把所有的元素中間用,隔開並組合成字串
toString() {
return `[${this.nums.join(',')}]`;
}
}
let nums1 = [[1,2],[3,4]]
let ex1 = new ArrayWrapper(nums1);
console.log(ex1.valueOf()); // 10
let nums2 = [[23,98,42,70]]
let ex2 = new ArrayWrapper(nums2);
console.log(ex2.toString()); //[23,98,42,70]
let nums3 = [[],[]]
let ex3 = new ArrayWrapper(nums3);
console.log(ex3.valueOf()); // 0