gpt4 book ai didi

javascript - 条件中的类型强制更危险吗?

转载 作者:行者123 更新时间:2023-12-03 10:36:12 25 4
gpt4 key购买 nike

我刚刚在 blog post 中读到了这篇文章:

If you want to coerce values, do so outside of the condition not within it.

我很好奇。在 Javascript 中,在条件条件中使用类型强制比在条件条件之外使用类型强制更糟糕吗?有副作用吗?

示例代码:

var initInt = 1
, initString = '1'

// Outside of a conditional
var coerceType = initInt == initString

if (coerceType === true) {
console.log('True')
}

// Inside of a conditional

if (initInt == initString) {
console.log('True')
}

最佳答案

他们的观点似乎很简单,您不应该使用 == 进行类型转换(或者根本不应该使用)。

在条件中使用类型强制是可以的,只要非常清楚发生了什么:

if (myNum === +myNumString)

但是 == 运算符有很多古怪、不一致且难以记住的行为,如该博客文章中所述。

正是由于这个原因,很多人建议完全不要使用 == 运算符。

Further Reading

关于javascript - 条件中的类型强制更危险吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28971236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com