2016-10-24 97 views
1

這裏是我正在努力的代碼。我想將這兩個輸入連接在一起,並將結果保存爲一個整數(JS中的數字)。JavaScript - 連接兩個數字並將結果視爲數字

var secsVal = -1; 
function valueAssign(i) { 

    if (secsVal == -1){ 

     document.getElementById("countdown").value = i; 
     document.getElementById("countdown").innerHTML = (i); 

     secsVal = i; 
    } 
    else {  
     secsVal = "" + secsVal + i;//concatenating first value of i to the second. 
     secsVal = secsVal.map(Number);//trying to convert back to num, but I think map() needs to see an array, which I don't think I got here. 

     document.getElementById("countdown").value = secsVal; 
     document.getElementById("countdown").innerHTML = (secsVal);//I want to replace the first displayed digit here, with the new (concatenated) number. 
    } 
} 
+0

不知道我理解你的要求。在HTML中,您可以存儲的是文本(不是數字或日期等JavaScript數據類型)。 –

+0

有沒有必要轉換回數字。 –

+0

你的意思是像數字(1 +''+'2')'? –

回答

1

這是沒有意義的使用數量在輸入標籤的值。該類型始終是一個字符串。

要轉換爲數字兼用Number或一元+

secsVal = Number(secsVal); 

secsVal = +secsVal; 
1

試試這個

secsVal = +("" + secsVal + i); 
0
secsVal = Number('' + secsVal + i) // explicit cast to number 
secsVal = +('' + secsVal + i)  // implicit cast to number 
secsVal = parseInt('' + secsVal + i) // explicit cast to integer 
secsVal = ~~('' + secsVal + i)  // implicit cast to integer 
0

只需使用+secsVal

var secsVal = -1; 
 
function valueAssign(i) { 
 

 
    if (secsVal == -1){ 
 

 
     document.getElementById("countdown").value = i; 
 
     document.getElementById("countdown").innerHTML = (i); 
 

 
     secsVal = i; 
 
    } 
 
    else {  
 
     secsVal = "" + secsVal + i; 
 
     console.log(typeof secsVal);//secsVal is a string 
 
     
 
     secsVal = +secsVal; 
 
     console.log(typeof secsVal); //secsVal is now a number 
 

 
     document.getElementById("countdown").value = secsVal; 
 
    } 
 
}
<input type="number" id="countdown"/> 
 
<button onclick="valueAssign(5)">Click</button>

相關問題