3 回答

TA貢獻1884條經(jīng)驗 獲得超4個贊
這是簡單的方法: var num = Number(str); 在此示例中,str是包含字符串的變量。您可以對其進行測試并查看其工作方式:Google chrome開發(fā)人員工具,然后轉(zhuǎn)到控制臺并粘貼以下代碼。閱讀評論以更好地了解轉(zhuǎn)換是如何完成的。
// Here Im creating my variable as a string
var str = "258";
// here im printing the string variable: str
console.log ( str );
// here Im using typeof , this tells me that the variable str is the type: string
console.log ("The variable str is type: " + typeof str);
// here is where the conversion happens
// Number will take the string in the parentesis and transform it to a variable num as type: number
var num = Number(str);
console.log ("The variable num is type: " + typeof num);
添加回答
舉報