2695. 包装数组


1.题目描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var ArrayWrapper = function (nums) {
this.nums = nums;
};
// 重写valueOf方法,使对象可以通过+运算符相加
ArrayWrapper.prototype.valueOf = function () {
if (this.nums.length === 0) {
return 0;
}
return this.nums.reduce((sum, num) => sum + num, 0);
};
// 重写 toString 方法,使对象在使用 String() 函数时返回逗号分隔的字符串
ArrayWrapper.prototype.toString = function () {
return `[${this.nums.join(",")}]`;
};

// 示例用法
const obj1 = new ArrayWrapper([1, 2]);
const obj2 = new ArrayWrapper([3, 4]);

console.log(obj1 + obj2); // 输出:10
console.log(String(obj1)); // 输出:"[1,2]"

const obj3 = new ArrayWrapper([23, 98, 42, 70]);
console.log(String(obj3)); // 输出:"[23,98,42,70]"

const obj4 = new ArrayWrapper([]);
const obj5 = new ArrayWrapper([]);
console.log(obj4 + obj5); // 输出:0