.value返回字符串,直到我将其保存到变量

.value return string until I save it to variable

本文关键字:保存 变量 value 字符串 返回      更新时间:2023-09-26

我有一个不确定如何解释的案例:让我头疼的是,我打开代码,写一些值(例如:你的账单是多少:100你的服务怎么样:10有多少人在分享:2)在我点击计算之前,我打开了控制台。如果我写:

>bill.value
<"100"

不出所料,我得到了一根绳子。但随后我点击"计算",得到的是:

100
5

为什么是100??为什么它突然返回数字而不是字符串?

我怎么能在最后用它做数学呢。我唯一要变成数字的是数字(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"