I recently encountered a question from js
. The question is like this. var str = 'abc' ;
typeof (str )
;
At first I thought the value returned was a String type value! But the result is Number, which makes me confused!
The idea I understand is that first split str , that is, str = str 1; Isn't this just string splicing? What is returned is still str.
But when I print out str, it is of NaN type. typeof(NaN)
is a Number type!
That is to sayconsole.log(str)
console.log(str = str 1)
is not equivalent!
Is that why? ?
某草草2017-06-12 09:33:29
Written in javascript advanced programming, ++
and --
are unary operators that increase and decrease. They can only operate on one data. They are different from the additive operator +
.
He will first The operand is converted to Number type, and then added or subtracted by one. So str = str+1
is not equal to str++
学习ing2017-06-12 09:33:29
Because when using str++, js has implicitly converted the string type of str into a numeric type
过去多啦不再A梦2017-06-12 09:33:29
console.log(str++) ++ will try to convert str into a number. If the automatic conversion is unsuccessful, it will become NaN
console.log(str = str+1) +At this time, try to splice the string and become abc1
黄舟2017-06-12 09:33:29
There is nothing in js that guarantees that a++ and a=a+1 are equivalent.
++
only has <number>
overloads, +
has <string, string>
and <number, number>
overloads. Even if behavior is not considered, types are no longer equivalent.
Other languages may have it, and it should not be confused with JS.
曾经蜡笔没有小新2017-06-12 09:33:29
First of all, your understanding is wrong. str++ is not completely equivalent to str+=1. Here it only needs to be understood as self-increment, but self-increment only applies to numbers, so str++ will perform implicit type conversion first, and the value of str is' abc' is NaN after conversion. The return value of typeof NaN is Number