我现在正在做一些调试,问题似乎是两个不兼容的类型(字符串和整数)被相乘在一起。现在,当这些乘积在一起时,将返回NaN结果。我想以一种模式运行代码,以便将不兼容的类型相乘在一起时会引发错误。我尝试在严格模式('use strict'
)中运行代码,但这没有用。我该怎么做?
console.log(2*'a')
> NaN
最佳答案
抛出自己的错误,并进行适当处理,例如:
try {
if(isNaN( 2*'a')) throw new Error("not a number");
}
catch(err) {
// handle error here
}
或检查变量的类型以适当处理,例如。
if (typeof(variableName) === "number")) {
console.log('variable is a number');
} else {
throw new Error('variable is NOT a number');
}