2012-02-22 80 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); 
} 
相關問題