JavaScript const用法介绍和示例

2021年3月13日16:35:42 发表评论 775 次浏览

ES2015(ES6)引入了const关键字来定义一个新变量。 const变量声明与其他变量声明的不同之处在于它无法重新分配。

特性:

  • 无法重新分配。
  • 区块范围
  • 可以在声明行的变量上分配它。
  • 原始值。
  • 可以更改const对象的属性, 但不能更改以引用新对象
  • const数组中的值可以更改, 可以将新项目添加到const数组中, 但不能引用新数组。
  • 允许在不同块范围内重新声明const变量。
  • 无法吊起。
  • 创建对值的只读引用。

范例1:它描述了const变量不能被重新分配。

<script type= "text/javascript" >
     const x = 12;
     x = 13;
     x += 1;
</script>

输出如下:

Uncaught TypeError: Assignment to constant variable.

范例2:它描述了包含Block Scope的const变量。

<script type= "text/javascript" >
     const x = 22;
     {
         const x = 90;
         console.log(x);
   
         {
             const x = 77;
             console.log(x);
         }
         {
             const x = 45;
             console.log(x);
         }
     }
     console.log(x);
</script>

输出如下:

90
77
45
22

范例3:它描述了const变量, 并在声明后分配了它。

<script type= "text/javascript" >
     const x;
     x = 12;
</script>

输出如下:

Uncaught SyntaxError: Missing initializer in const declaration

范例4:它描述了const变量不能被提升。

<script type= "text/javascript" >
     x = 3;
     console.log(x);
     const x;
</script>

输出如下:

Uncaught SyntaxError: Missing initializer in const declaration

范例5:它描述了只能修改对数组的引用才能修改数组值。

<script type= "text/javascript" >
  
     // Changing the content of array is
     // possible in cost array
     const arr1 = [ "pankaj" , "sumit" , "chandan" , "ajay" ];
      
     console.log(arr1.toString());
      
     arr1[2] = "Narayan" ; // possible
      
     console.log(arr1.toString());
</script>

输出如下:

pankaj, sumit, chandan, ajay
pankaj, sumit, Narayan, ajay

范例6:它描述了只能修改对对象的引用而不能修改的对象属性。

<script type= "text/javascript" >
  
     const person = {
         first_name: "Pankaj" , last_name: "Singh" , Age: 20, About: "Web Developer and Competitive Programmer"
     };
      
     console.log(person);
      
     // It is possible
     person.first_name = "Aryan" ;
     person.last_name = "Yadav" ;
     person.Age = 22;
     person.About = "Commerce undergraduate" ;
      
     console.log(person);
    
     // it is not possible
     // const person={
     //     "first_name":"Aryan", //     "last_name":"Yadav", //     "Age":22, //     "About":"Commerce undergraduate"
     // }
</script>

输出如下:

JavaScript const

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: