简体   繁体   English

对象可以是假的吗?

[英]Can an Object be false?

Is there any way to make an object return false in javascript?有没有办法让对象在javascript中返回false?

var obj = new Object();

console.log(!!obj) // prints "true" even if it's empty

No. An object that doesn't have any properties assigned is not considered "empty".不。没有分配任何属性的对象不被视为“空”。

The fact that a variable holds an instance of an object is enough to cause javascript to treat the variable as having the value of true when an expression requires a boolean value.当表达式需要布尔值时,变量保存对象实例的事实足以导致 javascript 将该变量视为具有true值。

Edit编辑

There are clearly some nuances to be cleared up looking at the other answers here.查看此处的其他答案,显然有一些细微差别需要澄清。

null is not an object, it is the distinct lack of an object. null不是一个对象,它是一个对象的明显缺失。 The question refers to an Object, that is one that has just been created.该问题涉及一个对象,即刚刚创建的对象。

As of ES8, no, you cannot make an object evaluates to false in JavaScript.从 ES8 开始,不,您不能在 JavaScript 中使对象评估为 false。

In the specification, all boolean checks ( ? ! if etc.) depends on ToBoolean ,在规范中,所有布尔检查( ? ! if等)都依赖于ToBoolean
which is very, very simple:这非常非常简单:

  • False if undefined, null, false, zero, NaN, or empty string.如果未定义,则为 False、null、false、零、NaN 或空字符串。
  • True for everything else (Object, Proxy, Symbol, etc.)对于其他所有内容(对象、代理、符号等)都是如此

If the type of the input is object, the result is true.如果输入的类型是对象,则结果为真。 No question asked.没有问任何问题。 No valueOf , no special case.没有valueOf ,没有特殊情况。

There is no way to create a falsy object in JavaScript.无法在 JavaScript 中创建虚假对象。 Only non-objects can be falsy.只有非对象可以为假。

Sometimes you may run into object-like "stuff" that return false.有时您可能会遇到返回 false 的类似对象的“东西”。 Empty string, for example, are used like an object all the time.空字符串,例如,使用对象的所有的时间。 document.all is another falsy "object". document.all是另一个虚假的“对象”。

These are not real objects, however.然而,这些都不是真实的物体。 They cannot have custom properties, cannot be used as prototype, and does not always behave like an object eg typeof or strict equal.它们不能有自定义属性,不能用作原型,并且并不总是像一个对象,例如 typeof 或严格相等。

This behaviour is most likely here to stay for backward compatibility.这种行为最有可能保留在这里以实现向后兼容性。

No. But null will convert to false .不。但null将转换为false

> typeof(null)
"object"
> null instanceof Object
false
> !!null
false

To see if the object contains any properties, use (shamelessly copied from How do I count a JavaScript object's attributes? ):要查看对象是否包含任何属性,请使用(无耻地复制自How do I count a JavaScript object's attributes? ):

function isEmpty (obj) {
    for (var k in obj) 
       if (obj.hasOwnProperty(k))
           return false;
    return true;
}

A null "object" (really value) will return false.一个空的“对象”(真正的值)将返回 false。

var obj = null;

console.log(!!obj);

If you wanted to check if it has no properties, you might try:如果您想检查它是否没有属性,您可以尝试:

var obj = new Object();
var empty = true;
for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
       empty = false;
       break;
    }
}
console.log(empty);

No.没有。

Not sure why you'd want this, but there is a way you could do something like this but it's kinda hacky...不知道为什么你要这样,但有一种方法,你可以做这样的事情,但它有点哈克...

var obj = {
    toString: function() { return ''; }
};

alert(!! (''+obj));

I think that with the first !我觉得用第一! you are casting obj to a boolean and negating its value- resulting in true if obj is null - , and with the second !您正在将 obj 转换为布尔值并否定其值 - 如果 obj 为 null 则为true - ,第二个! negating it again.再次否定它。

We can overwrite Object.prototype.valueOf to make an object appear to be false when it is coerced into a primitive, for example during == .我们可以覆盖Object.prototype.valueOf使对象在被强制转换为原始对象时看起来为 false,例如在==期间。

However it will not appear to be false when we force it into a boolean using !!然而,它不会出现,当我们使用武力它变成一个布尔值是假的!! , so it doesn't really work in the general case. ,所以它在一般情况下并不真正起作用。

var obj = {
    valueOf: function () {
        return false
    }
}

> obj == false
true               // Good, we fooled them!

> !!obj
true               // Not so good, we wanted false here

> Boolean(obj)
true               // Not so good, we wanted false here

Object-to-boolean conversions are trivial.对象到布尔值的转换是微不足道的。 All objects (including arrays and functions) convert to true.所有对象(包括数组和函数)都转换为 true。 This is so even for wrapper objects ( new Boolean(false) ) is an object rather than a primitive value, and so it converts to true .即使对于包装器对象new Boolean(false) )也是一个对象而不是原始值,因此它转换为true

In your case在你的情况下

console.log(!obj); will return false.将返回假。

because an object or an empty object is always a truthy.因为一个对象或一个空对象总是一个真值。

暂无
暂无

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

相关问题 如何将我的 object boolean 值更新为真假? - How can i update my object boolean value to true and false? 如果对象为空,如何将对象内部数组的内容设置为false? - How can I set the contents of an array inside an object to false if it is null? 删除对象中的false值 - Remove false values in object 强制对象评估为false - Force an object to evaluate to false 对象存在或对/错 - Object present or true/false 在JSON对象中:“ 0”是否为假? - From a JSON object: '0' is false? 我怎样才能返回一个空对象,同时在JavaScript中该空对象等于boolean false? - how can I return an empty object meanwhile the empty object equals to boolean false in javascript? 为什么JavaScript Object 的属性已经是configurable:false,writable 总是可以从true 变为false 而不会出错? - Why JavaScript Object's property is already configurable:false, writable can always be changed from true to false without error? How can I replace an object key:pair in an Object with a function that returns true or false depending on other properties in the same Object - How can I replace an object key:pair in an Object with a function that returns true or false depending on other properties in the same Object 可以使用带有真假键或逻辑运算符而不是单个 if else 的 object 来降低圈复杂度吗? - Can using an object with true and false keys or the logical operators instead of a single if else reduce cyclomatic complexity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM