变量声明
let 变量名称 = 值;
const 常量名称 = 值;
字符串
可以用单引号‘’,也可以用双引号“ ”
也可以使用字符串模版`The book price is ${bookPrice}`
javaScrip的内部类型
number(数值),string(字符串),boolean(布尔),symbol(独一无二的常数值).
bigint(大整数,超过正负2ⁿ-1 n=53)null(空值),undefinde(未定义),object(对象)
JavaScript的number实际上是64位双精度浮点数.
与其他语言的区别
以C#为例子,string productName = "变频器",命名变量时会强制要求填写变量的类型,先将变量名称productName定义为字符串类型,再将"变频器"这个字符串赋值给它,所有C#为静态类型的语言
但是Javascript的变量定义逻辑恰恰相反,有类型的是值的本身,而非变量,变量只是指向值的名称而已,所有javascript是动态类型的语言
Java Script的强制类型转换
示例代码
let bookPrice = 300
console.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 + penPrice
console.log(`Total price is ${totalPrice}`)
//运行结果
[Done] exited with code=0 in 0.134 seconds
[Running] node "f:\jstest\test.js"
book price is 300
pen price is 300
Prices are the same
Total price is 300300
[Done] exited with code=0 in 0.13 seconds
==是一般相等比较,它会先将二个值转换成相同类型,再进行比较
在上面的例子中,字符串会先被转换成数值,再进行比较,因此得到了`Prices are the same`的结果
如果两个值相加,其中一个为字符串,则另外一个也会被转成字串,然后二者链接起来
如果需要执行严格相等比较和将bookPrice,penPrice的值相加应该改写程序见下图:
let bookPrice = 300
console.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 300
pen price is 300
Prices are different
Total price is 600
[Done] exited with code=0 in 0.134 seconds
需要避免无意间的强制类型转换
使用===严格相等比较,值与类型都必须完全相等才会true
使用Number()函数将两个变量转换成数组,再进行相加
发表评论 取消回复