简体   繁体   English

更改 Javascript Object 的真/假值

[英]Change Truthy/Falsey value of Javascript Object

Basically can I do the following...基本上我可以做以下...

var obj = {}:
obj.falsey = true;
if(obj){
   //code not executed
}else{
   //code executed
}

I could take advantage of the fact !我可以利用这个事实! , + , ~ ... Call valueOf/toString and do the following, but I would like to avoid that. , + , ~ ... 调用valueOf/toString并执行以下操作,但我想避免这种情况。

var obj = {valueOf:function(){return 0}}:
obj.falsey = true;
if(!!obj){
   //code not executed
}else{
   //code executed
}

Why would I want to do this?我为什么要这样做? Because I'm curious:D因为我很好奇:D

No, you can't.不,你不能。 You have to implement some custom logic.您必须实现一些自定义逻辑。

You can borrow a false Number , Boolean .... from an iframe and extend its prototype.您可以从 iframe 借用一个错误的NumberBoolean .... 并扩展其原型。

Basically the following doesn't work because Numbers are a primitive value.基本上以下内容不起作用,因为 Numbers 是一个原始值。

var x = 0;
x.test = 'yo';
console.log(x.test);

This does, but obviously this pollutes the Number.prototype, so you should really borrow a different Number object from another iframe.确实如此,但显然这会污染 Number.prototype,所以你真的应该从另一个 iframe 借一个不同的Number object。

var x = 0;
Number.prototype.test = 'yo';
console.log(x.test);

Ultimately, just not a very good idea.最终,这不是一个好主意。

You can use loose equal to compare it to a boolean.您可以使用松散的等于将其与 boolean 进行比较。 People do that all the time, and finally it serves some purpose.人们一直这样做,最终它达到了某种目的。

var obj = {valueOf: function() {return !this.falsey;}};
obj.falsey = true;
if (obj == true) {
   //code not executed
} else if (obj == false) {
   //code executed
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM