首页 > 代码库 > js弱数据类型的坑

js弱数据类型的坑

1.从表单获取的value是字符串,如果需要为数字相加,则需要转换为number类型

<input type="number" id="val1">
<input type="number" id="val2">
<button id="btn">获取值</button>
<p id="Result"></p>
<script>
var input1=document.getElementById("val1");
var input2=document.getElementById("val2");
var Result=document.getElementById("Result");
document.getElementById("btn").addEventListener("click", function () {
var val1=input1.value;
var val2=input2.value;
Result.innerHTML=val1+val2//字符串的相加
})
</script>
2.数字的相加,如没有确定类型,最好多加一步转换为number类型相加
localStorage.setItem("num1",1);
localStorage.setItem("num2",1);
console.log(localStorage.getItem("num1")+localStorage.getItem("num2"))//11;
console.log(Number(localStorage.getItem("num1"))+Number(localStorage.getItem("num2")))//2


js弱数据类型的坑