编辑:为什么typeof(0)返回布尔值而不是数字

时间:2013-03-08 16:52:34

标签: javascript typeof

原始问题:我在使用JavaScript转换时遇到问题。这是一个例子:

var obj = {
    x: 0,
    y: 1,
    z: 2
}

var b1 = typeof (obj.x),
    b2 = typeof (obj.y),
    b3 = typeof (obj.z);

b1为"boolean",b2为"boolean",b3为"number"。 我需要将变量设置为0,我需要JavaScript将其解释为数字。我尝试过转换,例如b1 = Number(“0”),但它没有帮助:(

编辑:抱歉上面的q。这是真的。 b1,b2和b3全部返回号码。这是我的实际问题。

var SomeClass = function () {}
SomeClass.prototype = {
    element: {},
    startAt: 0,
    length: 2,
    get: function (prop) {
        if (typeof (prop) === "undefined" || !(typeof (prop) === "string")) {
            return false;
        }
        if (!this[prop]) {
            return false;
        }
        return this[prop];
    }
}

var sc = new SomeClass();
alert(typeof (sc.get("startAt")) + "\n" + typeof (sc.get("length")) + "\n" + typeof (sc.get("element")));

我想将startAt设置为数字。我很抱歉!!

1 个答案:

答案 0 :(得分:1)

  

我想将startAt设置为数字。

SomeClass.prototype.startAt 一个数字(0)。

如果属性为“falsey”,则get函数显式返回false

if(!this[prop]){return false;}

在JavaScript中,0""falseundefinednull都是“假的”,因此上述条件将为真并导致get返回false

如果您的目标是在不存在的情况下返回false,则可以这样做:

if (!(prop in this)) { return false; }

那将检查属性是否存在于对象本身其原型上,我怀疑它是你想要的。但是如果你只想检查对象本身并忽略原型上的属性,那就是:

if (!this.hasOwnProperty(prop)) { return false; }

如果你的目标是让getfalse返回get : function(prop){ if (typeof prop !== "string" || !(prop in this)) { return false; } return this[prop]; } 对象所没有的属性(无论是自己的属性,还是通过其原型),那么将所有这些结合起来,然后:

typeof

我在那里做了一些事情:

  1. "undefined"是一个运算符,而不是函数,所以你不要在它的操作数周围使用parens(通常)

  2. 由于!== "string"prop,因此在检查!(prop in this)是否为字符串时,无需专门检查。

  3. 我使用false来查看对象(或其原型)是否具有该属性。

  4. 我使用if将返回||的两个条件合并为一个{{1}}语句。

相关问题