.value return 字符串,直到我将它保存到变量

.value return string until I save it to variable

我遇到了不知道如何解释的情况: 让我烦恼的是,我打开代码,写了一些值(例如: 你的账单是多少:100 您的服务如何:10 有多少人在共享:2) 在我单击“计算”之前,我打开了控制台。如果我写:

>bill.value
<"100"

如预期的那样,我得到了一个字符串。但随后我单击“计算”,得到的结果是:

100
5

为什么是 100??为什么突然 return 数字变成了字符串?

最后我如何用它做数学运算。我唯一要变成数字的是 Number(bill.value)。服务和人应该还是字符串吧?

var button = document.querySelector("button");

var tip = document.getElementById("tip");

var total;


button.addEventListener("click", function() {

  var bill = document.querySelector("input");

  console.log(bill.value)

  var people = document.getElementById("people").value;

  var service = document.getElementsByTagName("select")[0].value;

  total = (service * Number(bill.value)) / people
  tip.textContent = total;
  console.log(total)
});
<h1>Tip Calculator</h1>

<div>How much was your bill?</div>

<label for="bill">$</label>
<input type="number" id="bill">



<div>How was your service?</div>

<select>
  <option disabled selected value="0">Choose</option>

  <option value="0.30">30% - Outstanding</option>
  <option value="0.20">20% - Good</option>
  <option value="0.15">15% - It was okaya</option>
  <option value="0.10">10% - Bad</option>
  <option value="0.05">5% - Terible</option>
</select>

<div>How many people are sharing the bill?</div>
<label>
  <input type="number" id="people">people</label>

<button>Calculate!</button>

<span id="tip"></span>

编辑:现在了解到您在询问隐式转换,我已经更新了我的答案。

看看下面的代码,您会注意到 product 保存的是一个数字值,而 sum 保存的是一个字符串。包含由 + 运算符分隔的两个字符串的表达式将始终导致字符串的连接(大多数人期望的)。

另一方面,* 运算符对两个字符串无效,因此它会尝试将字符串转换为支持 * 运算符的值,即数字。如果两个字符串都是有效的整数或浮点数,则结果是两个数字的乘积。否则,结果将为 NaN。

var a = '2.0';
var b = '3.0';

var sum = a + b;
var product = a * b;

console.log(product); // 6.0
console.log(sum); // "2.03.0"