简体   繁体   中英

Why is typeof my variable an object, and not a number

I have a table which has a couple cells that contain simple numbers (IE: 1.00, 1000.00, 10000.00). I'm trying to format the cell contents using the 'format' function below. I have had success with this function in a different area of my code, but for whatever reason (the reason why I'm here) when I try to feed the contents of the table cells in, it doesn't work as I expected.

The problem is that the typeof my cell contents is 'object' and not 'number', so it skates right by the if statement and just returns my original value back to me. Is there a way I can coerce the data to be typeof number? I thought var n = new Number(cellText); would do the trick, however, the typeof comes back as object. Confused.

In globalize.js:

Globalize.format = function( value, format, cultureSelector ) {
    culture = this.findClosestCulture( cultureSelector );
    if ( value instanceof Date ) {
        value = formatDate( value, format, culture );
    }
    else if ( typeof value === "number" ) {
        value = formatNumber( value, format, culture );
    }
    return value;
};

In my page:

$(document).ready(function () {
    $('td[globalize="true"]').each(function () {
        var $this = $(this);
        var cellText = $this.text();
        if (cellText != null) {
            var n = new Number(cellText);
            var v = Globalize.formatNumber(n, _gloNum[0]);
            $this.text(v);
        }
    })
});

The problem is that the typeof my cell contents is 'object' and not 'number'

When you do:

new Number

You are creating new instance of Number object, that's why it gives you object and not number.

Is there a way I can coerce the data to be typeof number?

var n = +(cellText);

Or

var n = Number(cellText);

In JavaScript new Number returns a Number object. Have a look at parseFloat or parseInt .

Change:

var n = new Number(cellText);

To

var n = Number(cellText);

Or

var n = parseFloat(cellText);

Or

var n = parseInt(cellText, 10);

Depending on what you need.

new Number(cellText) returns a Number object, not a number primitive.

Use parseInt or parseFloat instead.

var cellText = '12.34',
a = new Number(cellText), // 12.34, but a Number object
b = parseInt(cellText, 10), // 12
c = parseFloat(cellText); // 12.34

typeof a; // 'object'
a instanceof Number; // true

typeof b; // 'number'
typeof c; // 'number'

The typeof is buggy in JavaScript. I suggest you use the following function instead:

function typeOf(value) {
    if (value === null) return "null";
    else if (typeof value === "undefined") return "undefined";
    else return Object.prototype.toString.call(value).slice(8, -1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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