2012-02-22 76 views
2

我有一个包含简单数字(IE:1.00,1000.00,10000.00)的单元格的表格。我正在尝试使用下面的“格式”功能来格式化单元格内容。我已经在我的代码的不同区域成功使用了这个函数,但是当我尝试提供表格单元格的内容时,无论出于何种原因(我之所以来这里),它都无法正常工作。为什么键入我的变量对象,而不是数字

问题是我的单元格内容的类型是“对象”而不是“数字”,所以它通过if语句正确滑行,并将我的原始值返回给我。有什么办法可以强制数据是typeof数字吗?我认为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); 
     } 
    }) 
}); 

回答

5

的问题是,将typeof我的单元格的内容是 '对象',而不是 '数'

当你这样做:

new Number 

你正在创建实例号对象,这就是为什么它给你的对象而不是数字。

有没有办法强制数据是typeof数?

var n = +(cellText); 

或者

var n = Number(cellText); 
+0

这很好,谢谢! – HashTagDevDude 2012-02-22 17:42:17

+0

@hyperflow:不客气 – Sarfraz 2012-02-22 17:44:36

+0

这是最好的答案。它正确地显示了如何正确投射到数字原语。最好不要使用“新号码”。 – benekastah 2012-02-22 17:51:55

4

在JavaScript new Number返回Number对象。看看parseFloatparseInt

变化:

var n = new Number(cellText); 

var n = Number(cellText); 

或者

var n = parseFloat(cellText); 

或者

var n = parseInt(cellText, 10); 

d根据你的需要。

2

new Number(cellText)返回Number对象,而不是原始number

改为使用parseIntparseFloat

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' 
0

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); 
} 
相关问题