2017-01-11 101 views
0

我序列化如下形式(通過此answer啓發):解析號碼()

function formToArray(jQueryObj){ 
var result = {}; 
var arr = jQueryObj.serializeArray(); 
$.each(arr, function(){ 
    result[this.name] = this.value; 
}); 
return result; 
} 

這將返回一個對象如{"input1_name":"value1", "input2_name": "42"}。但是,一些輸入是數字的,我希望它們返回數字而不是字符串。所以我想要的輸出是{"input1_name":"value1", "input2_name": 42},這個數字沒有用引號。

如何通過jQuery/JavaScript實現此目的?

感謝,

回答

2

如果你想將字符串轉換回一個數字,你可以使用​​:

$.each(arr, function(){ 
    if (!isNaN(this.value)) { //check if value is convertible to number 
    result[this.name] = Number(this.value); 
    } else { 
    result[this.name] = this.value; 
    } 
}); 
+0

發現一個錯誤,當THIS.VALUE ===「0」,條件爲假 –

1

您可以手動檢查值數。

$.each(arr, function(){ 
    if (!isNaN(this.value)) { //Check for non numbers negation 
    result[this.name] = Number(this.value); 
    } else { 
    result[this.name] = this.value; 
    } 
}); 
1

解析值與isNaN

檢查
function formToArray(jQueryObj){ 
var result = {}; 
var arr = jQueryObj.serializeArray(); 
$.each(arr, function(){ 
    result[this.name] =isNaN(parseInt(this.value))?this.value:parseInt(this.value); 
}); 
return result; 
} 
1

你可以試試這個:

var result = { }; 
$.each($('form').serializeArray(), function() { 
    result[this.name] = Number(this.value) ? Number(this.value) : this.value; 
}); 
1

可以使用"string" * 1強迫多項

它比快使用NumberparseInt
還,如果使用parseInt記得傳遞基數10 parseInt(number, 10)

var converted = this.value*1; 
result[this.name] = isNaN(converted) ? this.value : converted;