当前位置:网站首页>How to perform implicit conversion in JS

How to perform implicit conversion in JS

2022-07-27 05:41:00 weixin_ forty-six million fifty-one thousand two hundred and si

ToPrimitive Method : This is a JS The method implicit in each value in the , Used to set the value ( Whether it's a basic type value or an object ) Convert to basic type value

If the value is a basic type , Then directly return the value itself ; If the value is an object , It probably looks like this :

ToPrimitive(obj,type)
obj–> Objects that need to be transformed
type–> Expected result type

type The value of can be number perhaps string, The default is number

1) When type by number The rules of time are as follows :

  • call obj Of valueof Method , If it's the original value , Then return to , Otherwise, the next step
  • call obj Of toString Method , If it's the original value , Then return to , Otherwise, the next step
  • Throw out typeError abnormal

2) When type by string The rules of tense are as follows :

  • call obj Of toString Method , If it's the original value , Then return to , Otherwise, the next step
  • call obj Of valueOf Method , If it's the original value , Then return to , Otherwise, the next step
  • Throw out typeError abnormal
var objToNumber=function(value){
    
            return Number(value.valueOf().toString())
        }
        console.log(objToNumber('')===0);//true
        console.log(objToNumber({
    })===NaN);//false
  1. + There is only one on either side of the operator string When type variable , Variables on both sides will be implicitly converted to strings ; In other cases, both variables will be converted to numbers
        console.log(1+'23');//123
        console.log(1+false);//1
        console.log('1'+false);//1false
        console.log(true+false);//1
  1. -、*、/ The operands are converted to numbers
        console.log(20-'5');//15
        console.log(1*false);//0
        console.log(1/'aa');//NaN
  1. ==, Cast data types , Equivalent unequal type
  2. about < and > Comparison symbol , Compare in alphabetical order
        console.log('a'>'b');//false
        console.log('aa'<'bc');//true
  1. In other cases , Convert to numbers and compare
        console.log(12<'13');//true
        console.log(false<-1);//false
  1. object
        var a={
    }
        console.log(a>2);//false
原网站

版权声明
本文为[weixin_ forty-six million fifty-one thousand two hundred and si]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/208/202207270502314895.html