【问题标题】:What is new Number(122) in Javascript [duplicate]Javascript中的新数字(122)是什么[重复]
【发布时间】:2021-11-14 22:07:48
【问题描述】:

我在这里看到一个问题 -> https://github.com/lydiahallie/javascript-questions#answer-c-1

考虑下面的代码 sn-p。

let a = 3;
let b = Number(3)
let c = new Number(3)

a == b // true
a === b // true
// but
a===c or b === c // false

上面的repo中也说明了这种情况,但是我想知道这个c对象的其他特点是什么。

我也试过在浏览器控制台查看它的属性或方法,发现和a一样,方法是toFixed, etc

【问题讨论】:

标签: javascript


【解决方案1】:

new Number 创建一个包装对象。

要获取其原始值,可以使用Number#valueOf

let a = 3, b = Number(3), c = new Number(3);

console.log(typeof c);

console.log(a === c.valueOf());
console.log(b === c.valueOf());

【讨论】:

    【解决方案2】:

    当您检查typeof 的所有值时,您将获得

    typeof a => number

    typeof b => number

    typeof c => object

    ===strict equality,所以它会检查它的typevalue

    1)如果你想检查相等性,你可以使用a == cb == c

    2)使用cvalueOf方法,与ab比较为:

    a === c.valueOf();
    b === c.valueOf();
    

    let a = 3;
    let b = Number(3);
    let c = new Number(3);
    
    console.log(typeof a === "number"); // true
    console.log(typeof b === "number"); // true
    console.log(typeof c === "number"); // false
    console.log(typeof c === "object"); // true
    
    console.log(a == c);
    console.log(b == c);
    console.log(a === c);
    console.log(b === c);
    
    console.log(a === c.valueOf());
    console.log(b === c.valueOf());
    /* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案3】:

      因为

      let a = 3; // is a number
      let b = Number(3) // is a number
      let c = new Number(3) // is an object
      
      a == b // true
      a === b // true
      // but
      a===c or b === c // false
      

      清楚吗?

      【讨论】:

      • 我已经说过 The situation is also explained in the above repo -> here 明确指出 new Number() 是一个对象。但是,我对这个对象的其他功能感兴趣。我找到的答案是,new Number() 将创建一个围绕本机 Integer 类型的 Object 包装器,就像 Java 包装器一样。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 2013-05-05
      • 2012-09-06
      • 2017-09-25
      • 2018-08-08
      • 1970-01-01
      相关资源
      最近更新 更多