.value返回字符串,直到我将其保存到变量
.value return string until I save it to variable
我有一个不确定如何解释的案例:让我头疼的是,我打开代码,写一些值(例如:你的账单是多少: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"
相关文章:
- 如何将getJson的响应保存在全局变量中
- 为所有查看网站的用户保存变量
- 关闭浏览器后保存变量
- 无法在Node.JS中保存变量
- 在 while 循环中保存变量
- 如何在移动到新的HTML页面后使用保存在Javascript文件中的保存变量
- PHP 会话不通过多个页面保存变量
- 保存变量
- 通过单击图像保存变量
- 在javascript中 - 保存变量作为参考
- 使用JavaScript onclick删除元素,并在SQL中保存变量
- 在cookie中保存变量- console.log返回具有会话id的变量
- JavaScript:在调用之间保存变量的值
- 如何在hta中保存变量,以便在关闭和打开hta后保存
- 在闭包中保存变量内容有问题
- 当html页面发生变化时,如何保存变量的状态
- 在闭包范围中保存变量
- Javascript 在使用 XMLHttpRequest 时通过作用域保存变量
- 在 cookie 中查找并保存变量
- 保存变量的值