Analysis of the meaning of the plus sign + in front of the variable in JS

javascript You often see a plus sign in front of the variable  + , what is the use of it? In fact, it is very simple, that is 把变量转换成 number 类型(in addition, the variable - 0  is also a way of converting the value of the variable into a numerical value). Not much to say, let's look at the following examples to help you understand intuitively:

// null:返回 0
console.info(+null) // => 0

// undefined:返回 NaN
console.info(+undefined) // => NaN

// 获取当前的时间戳,相当于`new Date().getTime()`
console.info(+new Date())

// 布尔型转换为整型:true 返回 1,false 返回 0
console.info(+true) // => 1
console.info(+false) // => 0

// 空字符串:返回0
console.info(+'') // => 0

// 忽略前面的 0
console.info(+'010') // => 10

// 16进制转换成 10进制
console.info(+'0x3E8') // => 1000

// 科学计数法自动解析
console.info(+'1e3') // => 1000
console.info(+'1e-3') // => 0.001

// 无法解析的格式:返回 null
console.info(+'1,000') // => NaN

At this point, everyone should understand, in fact, it is equivalent to

Number(value)

It will be converted to a value or NaN according to the rules of the Number function. The rules are roughly as follows:

  • Boolean: true returns 1, false returns 0
  • Data value, return directly
  • null, return 0
  • undefined, returns NaN
  • For a string, convert it to a decimal value, ignore the leading 0 (except for hexadecimal), return 0 for an empty string, and return a floating point value for a floating point number. Other format strings (regardless of starting with a number, return NaN, multiple decimal points in the string, return NaN)

Guess you like

Origin blog.csdn.net/sunyctf/article/details/131273674
Recommended