xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

JavaScript Object valueOf & toString All In One

JavaScript Object valueOf & toString All In One

Object.prototype.valueOf() & Object.prototype.toString()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf

The valueOf() method of Object instances converts the this value to an object. This method is meant to be overridden by derived objects for custom type conversion logic.

Object 实例的 valueOf() 方法将 this 值转换为对象。此方法旨在由派生对象重写以实现自定义类型转换逻辑。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/valueOf

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString

Instance methods

~https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/valueOf~ ❌

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf

demos

class ArrayWrapper {
  arr: number[];
  constructor(nums: number[]) {
    this.arr = nums;
  }
  // ✅ 改写 Object 内置方法 valueOf, 返回一个 number 整数 
  // ❓ object 相加 (本质上是 object 序列化后的 string 相加 ✅) => number 相加
  valueOf(): number {
    return this.arr.reduce((sum, i) => sum + i, 0);
  }
  // 序列化
  toString(): string {
    // return JSON.stringify(arr);
    return `[${this.arr.join(',')}]`;
  }
};



/**
 * const obj1 = new ArrayWrapper([1,2]);
 * const obj2 = new ArrayWrapper([3,4]);
 * obj1 + obj2; // 10
 * String(obj1); // "[1,2]"
 * String(obj2); // "[3,4]"
 */

https://leetcode.com/problems/array-wrapper/submissions/1258562707/?envType=study-plan-v2&envId=30-days-of-javascript

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2024-05-15 17:07  xgqfrms  阅读(3)  评论(0编辑  收藏  举报