![](/img/trans.png)
[英]Why is typeof Object,String,Number… -a function in Javascript
[英]Why is typeof my variable an object, and not a number
我有一个表有几个包含简单数字的单元格(IE:1.00,1000.00,10000.00)。 我正在尝试使用下面的“格式”功能格式化单元格内容。 我已经在我的代码的不同区域成功使用了这个函数,但出于任何原因(我之所以在这里),当我尝试提供表格单元格的内容时,它不能像我预期的那样工作。
问题是我的单元格内容的类型是'对象'而不是'数字',所以它通过if语句滑动,然后将原始值返回给我。 有没有办法可以强制数据为数字类型? 我以为var n = new Number(cellText);
会做的伎俩,然而,typeof作为对象返回。 困惑。
在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;
};
在我的页面中:
$(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);
}
})
});
问题是我的单元格内容的类型是“对象”而不是“数字”
当你这样做时:
new Number
您正在创建Number对象的新实例,这就是它为您提供对象而不是数字的原因。
有没有办法可以强制数据为数字类型?
var n = +(cellText);
要么
var n = Number(cellText);
在JavaScript中, new Number
返回一个Number对象。 看看parseFloat
或parseInt
。
更改:
var n = new Number(cellText);
至
var n = Number(cellText);
要么
var n = parseFloat(cellText);
要么
var n = parseInt(cellText, 10);
根据您的需要而定。
new Number(cellText)
返回一个Number
对象,而不是一个number
原语。
请改用parseInt
或parseFloat
。
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'
该typeof
是JavaScript的越野车。 我建议您使用以下功能:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.