如何将字符串转为数字?表单对象age字段类型转换问题求助
Hey there! I see the problem—your form's age value is coming through as a string ('22') instead of a number (22), and that's totally expected because all form input values are returned as strings by default. Let's fix this and also cover the common ways to convert strings to numbers in JavaScript.
Step 1: Modify Your formObj Function
We can add a check for the age field specifically and convert its value to a number before assigning it to the form object. Here's the updated code:
function formObj(elems) { let form = {}; for(let elem of elems) { let key = elem.id; let val = elem.value; if(key && val) { // Convert 'age' value to number, keep others as-is form[key] = key === 'age' ? Number(val) : val; } } return form; } let elements = document.querySelectorAll('form *') const result = formObj(elements); console.log(result); // {name: "Harry", email: "harry@gmail.com", age: 22}
If you have other fields that need to be numbers (like a height or zipcode field), you can expand the condition—for example, using an array of number field IDs:
const numberFields = ['age', 'height']; form[key] = numberFields.includes(key) ? Number(val) : val;
Step 2: Common Ways to Convert Strings to Numbers in JavaScript
Here are the most reliable methods you can use, depending on your needs:
Number(): The go-to method for strict conversion. It returns a number if the string is a valid number,0for empty strings, andNaNfor non-numeric strings.Number('22') // 22 Number('22.5') // 22.5 Number('abc') // NaNparseInt(): Perfect for extracting integers from strings. It ignores non-numeric characters after the number, and always specify base10to avoid unexpected behavior with hex/octal values.parseInt('22') // 22 parseInt('22abc') // 22 parseInt('22.99') // 22 parseInt('22', 10) // 22 (recommended)parseFloat(): Similar toparseInt(), but handles floating-point numbers:parseFloat('22.99') // 22.99 parseFloat('22abc') // 22Unary
+operator: A concise alternative toNumber()with identical behavior:+'22' // 22 +'22.5' // 22.5 +'' // 0
Pro Tip: Handle Invalid Inputs
If you want to avoid storing NaN when the user enters non-numeric text for age, add a check to fall back to the original string or a default value:
form[key] = key === 'age' ? (!isNaN(Number(val)) ? Number(val) : val) : val;
That should solve your problem! Let me know if you need further tweaks.
内容的提问来源于stack exchange,提问作者muhammad

