[JS] base type conversion Know

appetizer

Let me talk a digression, I encountered a problem at work, you need to compare "08:00"and "09:00"size, and finally I found three ways:

  1. Comparing the same two respective longitudinal string and second splicing date, makes up a complete time format:
var head = "2016-01-01 "
var foot = ":00"

var time1 = head + "08:00" + foot //"2016-01-01 08:00:00"
var time2 = head + "09:00" + foot //"2016-01-01 09:00:00"
复制代码

The rest did not say, comparing two full date is still very easy.

  1. The two strings of the colon is removed, converted into digital compared:
function timeToNumber(time) {
    let [head,foot] = time.split(":")
    return Number(head+foot)
}

var time1 = timeToNumber("08:00") //800
var time2 = timeToNumber("09:00") //900
复制代码
  1. Direct comparison

Yes, you read right, a direct comparison of two strings:

"08:00" > "09:00" //false
复制代码

See here estimated that some people wonder, it is clear that the third method is more concise, but the string comparison, it seems rare, it is based on any more of it?

In fact, compare the size of the string, from left to right will take two strings of characters, pairwise comparison of their charCodeAt()results, compare the size until it stops. such as:

var str1 = "a11"
var str2 = "a2"
// str1 和 str2 比较的时候,会先比较 str1[0] 和 str2[0],两个都是 "a",比较下一个
// str1[1] 是"1",charCodeAt()是49,str2[1] 是"2",结果是50,所以 str1[1] < str2[1],对比结束
// 最终结果 str1 < str2 
复制代码

Similarly, in comparison "08:00", and "09:00"when the first comparison of the two "0", was found after relatively consistent "8"and "9", so "08:00" < "09:00".

There is a problem is, time formats must be consistent , not enough to remember the number of bits up "0", take "8:00"and "10:00"compare the findings will have a problem, we must take "08:00"and "10:00"compare can.

Here the problem is, there are other ways you can leave a message to add, to provide different ideas. Appetizer end, that is entered.

Thesis

As a love (remember) school (not) study (clear) good (stupid) children, through it, I realized that more comparisons string comparisons as well as non-identical types, such as strings and numbers compare comparison and Boolean arrays (I'm crazy so what I use), in addition to addition, subtraction and other operators.

I feel the need to tidy up.

My first reaction was this picture:

It is really charming smile :)

Before the comparison, we need to first understand the results of various data types into what.

To Digital

  • String:
    • An empty string is 0
    • Head and tail string spaces will be ignored
    • A space containing a non-numeric characters, in the middle of the conversion result, or the string isNaN
  • Boolean: true -> 1,false -> 0
  • undefined字: NaN
  • null: 0
  • Array:
    • Empty array is 0
    • If the array has one and only one is a number of elements, converted to digital
    • Other casesNaN
  • Object:
    • If the object has a valueOf()method, it calls the method. If the return type of the basic value, this value will be converted to digital
    • If the object does valueOf()not substantially method or a type value returned by the method, the object is invoked toString()method. If there is a basic type of the return value and the value is converted to digital
    • Otherwise error
  • function:NaN

To String

  • undefined -> "undefined"
  • null ->"null"
  • true -> "true" / false ->"false"
  • Digital: minimum and maximum numbers using exponential form, you know the general situation
  • Object:
    • If the object has a toString()method, it calls toString()the method. If the method returns a primitive type value, this value will be converted to a string
    • If the object does toString()not substantially method or a type value returned by the method, the object is invoked valueOf()method. If the return value is present and the type of the basic value, it is converted to a string
    • Otherwise error
    • Unless self defined otherwise, toString()it returns the internal attribute [[Class]]values, such as"[object Object]"

Turn Boolean

  • All false value undefined( null, +0, -0, NaN, , "") will be converted to falsethe other will be convertedtrue
  • So, empty object is an empty arraytrue

Turn objects

  • nullAnd undefinedturn objects directly Throws
  • Basic types by calling String(), Number(), Boolean()constructors, converted to their respective wrapper object

scenes to be used

Know the rules of the various data type conversion, then the different scenarios, whether it is how to use it?

Operator ==

Common errors are: ==check values are equal, ===check the value and type are equal.

Correct interpretation is: ==allowed casts equal comparison, and ===are not allowed.

In fact, ==and ===the type of checking operation will be the number, not the same except that a different type of treatment thereof.

  1. If a value of nullthe other value undefinedis equal to
  2. If a string, the other value is a number, put the string into a digital, compared
  3. If any value true, put trueconverted into 1 then compared; if any value false, put falseconverted into 0 then compared
  4. If an object, other numeric or string, the value of the underlying object into another type of comparison
    • When the object-type basis, priority call valueOf(), then call toString().
    • The exception is Date, Datethe use of a toString()conversion

Classic title

[] == false // true
!![] // true

//原因是 == 两边都转为数字进行比较,而不是 [] 转为布尔值与 false 比较
复制代码

Operator +

+ Operator can be used as a unary operator, acting at this time is to follow the data back to digital

+true // 1
+[] // 0
+new Date() //获取当前时间的Unix时间戳
复制代码

When used as a binary operator, +operator than the - * /operator is more complicated, because all the other operators of the digital processing, the +operator can also handle string concatenation.

  • If both sides of the string, the other side will be converted to a string adding
  • If no string, both sides will be adding to digital conversion, digital conversion is also an object of the foregoing method
  • If one of the operands is an object, the object is converted to the original value, objects by date toString()converting method, other objects by valueOf()converting method, but most do not have all the available valueOf()methods, it is still by toString()performing conversion method

Simply means that, if +the operator of one of the operands is a string (or character string can be obtained by the above step), then performs string concatenation, else the digital adder.

Classic title

!+[]+[]+![] //"truefalse"

//首先第一个 + 左边不是数值,所以它是一元运算符,将后边跟着的 [] 转化为数字 0
//同时,最后一个 [] 左边是 ! 运算符,将 [] 转化为布尔值并取反,为 false
//转化后的结果为 !0 + [] + false
//!0 结果为 true,[] 转化为 "",所以结果变为 true + "" + false
//因为 第一个 + 右边有字符串,所以变为"true" + false
//最终结果为 "truefalse"
复制代码

Conditional

The following conditional statement occurs implicitly converted to Boolean values ​​where:

  • if()Statement conditional expression
  • for(..; ..; ..)Statement conditional expression
  • while()withdo .. while()
  • ? :The conditional expression
  • ||And &&the left operand

Supplementary: valueOf () and toString ()

Common built-in objects call toString()and valueOf()returned the case

Types of
Object "[Object type name]" The object itself
String String value String value
Number Returns the string representation. Also return the specified string in hexadecimal, decimal default Numeric value
Boolean "true" / "false" Boolean value
Array Each element into a string, stitching comma as a delimiter Array itself
Date Text representation of the date in the format Wed Jun 05 2019 18:22:32 GMT + 0800 (China Standard Time) Returns the timestamp, is equivalent to calling getTime ()
Function Text functions representation Function itself
RegExp Regular text representation Regular itself

These are the contents of this article are welcome to put forward their own ideas, we learn and progress together, and the king of mutual encouragement.

Reference material

Reproduced in: https: //juejin.im/post/5cf79a09f265da1b8f1ab05d

Guess you like

Origin blog.csdn.net/weixin_34221276/article/details/91455834