Type coercion - MDN Web Docs Glossary: Definitions of Web-related terms 编辑
Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers). Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.
Examples
const value1 = '5';
const value2 = 9;
let sum = value1 + value2;
console.log(sum);
In the above example, JavaScript has coerced the 9
from a number into a string and then concatenated the two values together, resulting in a string of 59
. JavaScript had a choice between a string or a number and decided to use a string.
The compiler could have coerced the 5
into a number and returned a sum of 14
, but it did not. To return this result, you'd have to explicitly convert the 5
to a number using the Number()
method:
sum = Number(value1) + value2;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论