为什么我需要parseInt()来避免NaN?

agr*_*son 1 javascript parseint

我有一个带有2个值的2D数组,我想用一条小信息打印差异.

var array = [[0,2],[3,4]];
console.log(array[0][1]-array[0][0]) //prints '2'
console.log(array[0][1]-array[0][0] + ' is the number') //prints '2 is the number'
console.log('The number is' + array[0][1]-array[0][0]) //prints 'NaN'
console.log('The number is ' + parseInt(array[0][1]-array[0][0], 10)) //prints 'The number is 2'
Run Code Online (Sandbox Code Playgroud)

为什么我需要在结果之前parseInt()打印一条消息,但是在结果之后打印文本,或者仅仅是结果打印,是否可以?

Nie*_*sol 7

实际上,parseInt没有区别.它将减法放在重要的括号中.

你的代码基本上是说:

"The number is" + array[0][1]-array[0][0]
// becomes...
"The number is 2"-array[0][0]
// is cast to...
parseInt("The number is 2")-array[0][0];
// which is...
NaN-0
// or just...
NaN
Run Code Online (Sandbox Code Playgroud)

这都是关于操作的顺序.