对象类型转换Javascript

对象类型转换Javascript,javascript,Javascript,我正在学习Javascript。我正在尝试转换对象。在尝试转换时,它只打印数字而不是字符串。打印字符串时,显示完整的对象,而不是字符串。下面是我的代码 let user2={ 名称:“阿卡什”, 姓氏:“Jangra”, 年龄:30,, 工资:25000, [Symbol.toPrimitive](提示){ log(`hint:${hint}`); return-hint==“string”?`{name:${this.name}},${this.name}`:this.Salary; } }

我正在学习Javascript。我正在尝试转换对象。在尝试转换时,它只打印数字而不是字符串。打印字符串时,显示完整的对象,而不是字符串。下面是我的代码

let user2={
名称:“阿卡什”,
姓氏:“Jangra”,
年龄:30,,
工资:25000,
[Symbol.toPrimitive](提示){
log(`hint:${hint}`);
return-hint==“string”?`{name:${this.name}},${this.name}`:this.Salary;
}
};
console.log(user2);
console.log(+user2);
console.log(user2+500)试试看

当你这样做的时候

console.log('' + user2);
提示等于默认值

您必须“告诉”JavaScript要显式转换为什么。 示例:

var x = { test: 1 };

// Console log the object
console.log(x);

// Try to convert to number
console.log(0 + x);

// Try to convert to string
console.log(`${x}`);

// I thought this would work as wel, but is does not convert to 'string' but to 'default'
console.log('' + x);

// Try to bool
console.log(!!x);


编辑:就像埃佐托斯说的。这在javascript中是非常罕见的。

这实际上是一种非常罕见的做法。JavaScript中的对象通常保持原语。因此,只包含数据

我建议创建一个函数,将源对象作为参数,并返回所需的输出

如果您需要此类对象中的功能,请考虑改用

例如,重载toString()方法

var x = { test: 1 };

// Console log the object
console.log(x);

// Try to convert to number
console.log(0 + x);

// Try to convert to string
console.log(`${x}`);

// I thought this would work as wel, but is does not convert to 'string' but to 'default'
console.log('' + x);

// Try to bool
console.log(!!x);