变量声明

  1. let 变量名称  = 值;

  2. const 常量名称 = 值;

字符串

  1. 可以用单引号‘’,也可以用双引号“ ”

  2. 也可以使用字符串模版`The book price is ${bookPrice}`

javaScrip的内部类型

  1. number(数值),string(字符串),boolean(布尔),symbol(独一无二的常数值).

  2. bigint(大整数,超过正负2ⁿ-1 n=53)null(空值),undefinde(未定义),object(对象)

  3. JavaScript的number实际上是64位双精度浮点数.

与其他语言的区别

  1. 以C#为例子,string productName = "变频器",命名变量时会强制要求填写变量的类型,先将变量名称productName定义为字符串类型,再将"变频器"这个字符串赋值给它,所有C#为静态类型的语言

  2. 但是Javascript的变量定义逻辑恰恰相反,有类型的是值的本身,而非变量,变量只是指向值的名称而已,所有javascript是动态类型的语言

Java Script的强制类型转换

示例代码

let bookPrice = 300console.log(`book price is ${bookPrice}`)let penPrice = "300"console.log(`pen price is ${penPrice}`)if(bookPrice == penPrice){  console.log('Prices are the same')}else{  console.log('Prices are different')}let totalPrice = bookPrice + penPriceconsole.log(`Total price is ${totalPrice}`)
//运行结果[Done] exited with code=0 in 0.134 seconds[Running] node "f:\jstest\test.js"book price is 300pen price is 300Prices are the sameTotal price is 300300[Done] exited with code=0 in 0.13 seconds
  1. ==是一般相等比较,它会先将二个值转换成相同类型,再进行比较

  2. 在上面的例子中,字符串会先被转换成数值,再进行比较,因此得到了`Prices are the same`的结果

  3. 如果两个值相加,其中一个为字符串,则另外一个也会被转成字串,然后二者链接起来

  4. 如果需要执行严格相等比较和将bookPrice,penPrice的值相加应该改写程序见下图:

let bookPrice = 300console.log(`book price is ${bookPrice}`)let penPrice = "300"console.log(`pen price is ${penPrice}`)if(bookPrice === penPrice){  console.log('Prices are the same')}else{  console.log('Prices are different')}let totalPrice = Number(bookPrice) + Number(penPrice)console.log(`Total price is ${totalPrice}`)//运行结果[Running] node "f:\jstest\test.js"book price is 300pen price is 300Prices are differentTotal price is 600[Done] exited with code=0 in 0.134 seconds
  1. 需要避免无意间的强制类型转换

  2. 使用===严格相等比较,值与类型都必须完全相等才会true

  3. 使用Number()函数将两个变量转换成数组,再进行相加



点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部