如何将字符串更改为数字

时间:2019-10-09 14:13:34

标签: javascript

我对某些代码有疑问。我需要它来返回这样的对象:

{name: "Harry, email: "harry@gmail.com", age: 22}
//age is 22 a number not '22' a string 

但是它会像这样返回:

{name: "Harry, email: "harry@gmail.com", age: '22'} 

这是我的代码

function formObj(elems) {
  let form = {};
  for(let elem of elems) {
    let key = elem.id;
    let val = elem.value;
    if(key && val)
      form[key] = val;
  }
  return form;
}

let elements = document.querySelectorAll('form *') 
formObj(elements);
<form>
    <label for='name'>name</label>
    <input type='text' id='name' value="Harry"/>

    <label for='email'>email</label>
    <input type='email' id='email' value="harry@gmail.com"/>

    <label for='age'>age</label>
    <input type='text' id='age' value="22"/>
<form/>

请帮忙

2 个答案:

答案 0 :(得分:2)

您可以将键的类型更改为function formObj(elems) { let form = {}; for(let elem of elems) { let key = elem.id; let val = elem.value; if(key && val) form[key] = key ==="age" ? Number(val) : val; } console.log(form) return form; } let elements = document.querySelectorAll('form *') formObj(elements);

<form>
    <label for='name'>name</label>
    <input type='text' id='name' value="Harry"/>

    <label for='email'>email</label>
    <input type='email' id='email' value="harry@gmail.com"/>

    <label for='age'>age</label>
    <input type='text' id='age' value="22"/>
<form/>
master_data_long_sub[,freq:=uniqueN(Demand),by=.(Material)]

答案 1 :(得分:0)

如果您将“年龄”输入的类型更改为数字,那么您应该会得到所需的结果,例如

public static void main (String[]args)
{
  String plainText = textScanner.scanner();
  encryptor.toHexadecimal(plainText);
}