【JavaScript学习】JavaScript变量详解

变量

介绍

变量即变化的量,用以存储程序执行过程中的一些数据
在JavaScirpt中,这点更加得以体现

例如:

let x
x = 1
console.log(typeof x)	// 输出结果:number
x = "Hello World"
console.log(typeof x) // 输出结果:string
x = true	
console.log(typeof x) // 输出结果:boolean

我们只需要开辟一个存储空间 x,
便可以将任意类型的数据放入存储空间x内。

变量类型

  • 常用类型:
    • Number:数字类型(所有的数字皆为数字型,无论是整数还是小数/浮点数)
    • String:字符串类型
    • Boolean:布尔类型
  • 其他类型:
    • Undefined:未被定义型
    • Symbol:唯一型
    • BigInt:长数字型
    • Object:对象型
    • Array:数组型
  • 获取变量类型的函数:typeof
    • 例:
      console.log(typeof true)
      console.log(typeof 23)
      console.log(typeof "String")
      console.log(typeof test)
      console.log(typeof null)
      /*
          输出结果:
              boolean
              number
              string
              undefined
              object
       */
      

声明关键字

声明变量的关键字有 let var const,但他们之间存在着一些区别

  • var:局部全局变量

    • 作用域:var的作用域既可以是全局或者整个函数块(注意:不包括{}包裹的代码块)
    • 样例:
      var x = 1
      if(x==1){
              
              
          var x = 2;
          console.log(x);
      }
      console.log(x);
      
       */
      
      输出结果:
          2
          2
      分析:
          因为var的作用域为全局或整个函数块,
          在if{}限定的代码块中用var定义的x会自动扩展至外层,
          所以会输出两个2
      
  • let:普通变量

    • 作用域:let的作用域既可以是全局或者整个函数块,也可以是 if、while、switch等用{}限定的代码块。
    • 样例:
      let x = 1
      if(x==1){
              
              
          let x = 2;
          console.log(x);
      }
      console.log(x);
      
       输出结果:
          2
          1
       分析:
          因为let的作用域既可以是全局或者整个函数块,
          也可以是 if、while、switch等用{}限定的代码块,
          所以在if{}限定的代码块中用let定义的x不会扩展,
          因此输出一个2,一个1
      
  • const:静态变量

    • 作用域:const的作用域既可以是全局或者整个函数块,也可以是 if、while、switch等用{}限定的代码块。
    • 样例:
      const x = 1
      try{
              
              
        x = 2
      }catch(error){
              
              
        console.log(error)
      }
      console.log(x)
      
       输出结果:
          TypeError: Assignment to constant variable.
          1
       分析:
          因为const是静态变量,一旦指定,地址不可更改
          因此x重新赋值会报错
          x仍然等于1
      

命名规则

  • 变量名称可包含字母、数字、下划线和美元符号
  • 变量名称必须以字母$_ 开头
  • 变量名称对大小写敏感(y 和 Y 是不同的变量)
  • JavaScript关键字无法用作变量名称

猜你喜欢

转载自blog.csdn.net/qq_62094479/article/details/129810142