【问题标题】:compare primitive datatype and object datatype in javascript [duplicate]比较javascript中的原始数据类型和对象数据类型[重复]
【发布时间】:2020-05-07 17:18:44
【问题描述】:

我想用equals方法比较两个对象:

class test{

    constructor(name, year) {
        this.name= name;
        this.year= year;

        if (year== 0) {
            this.year= -1;
        }
    }

    equals(a){
        if(this.year!= a.year){
            return false;
        } 
        if(this.name!= a.name){
            return false
        }
        return true;
    }

如果我调用类测试的新对象:

let a1 = new test("Hey",22);
let a2 = new test("Hey",22);

它适用于:

console.log(a1.equals(a2)); --> gives me true

但如果我在测试对象中生成一个新字符串:

let a1 = new test(new String("Hey"),22);
let a2 = new test(new String("Hey"),22);

equals 方法的输出给了我错误:

console.log(a1.equals(a2)); --> gives me false;

如何修复 equals 方法,以便它也比较 String 类型的新对象?

【问题讨论】:

    标签: javascript object compare equals


    【解决方案1】:

    请看下面的例子:

    var s = 'foo';
    var s_obj = new String(s);
    var s_obj2 = new String(s);
    
    console.log(typeof s); 
    console.log(typeof s_obj);  
    
    console.log(s)
    console.log(s_obj)
    console.log(s_obj.valueOf())
    
    // funny effects:
    console.log(s_obj==s) // true 
    console.log(s==s_obj) // true
    console.log(s_obj==s_obj2) // false
    console.log(s_obj.valueOf()==s) // true
    console.log(s_obj.valueOf()==s_obj2.valueOf()) // true

    如果你比较两个新的 String 对象,你不是在比较它们内部的值,而是对象实例

    【讨论】:

    • 如果 typeof 名称是对象(a.name 和 this.name 都是),那么您必须使用 .valueOf。我编辑我的例子给你一些有趣的 console.log
    猜你喜欢
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多