ES6 解释常量

ES6 解释常量

JavaScript是世界上最流行的轻量级、解释性编译式编程语言。它也被称为网页脚本语言。它以开发网页而闻名,许多非浏览器环境也使用它。JavaScript既可以用于客户端开发,也可以用于服务器端开发。

Const关键字: 在编程中,我们会遇到一些情况,我们想要声明一个变量,其值在整个程序中保持不变。一个示例是pi的值始终保持不变。ES6支持这样一种声明,可以使用关键字const 来声明。

声明 const 变量的语法如下:

const CONST_NAME = value;

Const的特性:

  • 使用const声明的变量是不可变的
  • 使用const声明的变量具有块级作用域
  • 使用const声明的变量不能被重新分配
  • 使用const声明的变量必须在声明时立即赋值。
  • 使用const声明的变量在声明之前不能使用。

下面的示例将展示使用const关键字的各种特性。

示例1: 在这个示例中,将会抛出一个错误,显示”正在尝试覆盖常量’i'”,因此,这表明使用const声明的变量不能被覆盖。

JavaScript

<script> 
    const myFunc = function () { 
        const i = 5; 
  
        try { 
  
            // The below line will throw an error 
            i = i + 2; 
        } 
        catch (error) { 
            console.log(error) 
        } 
    } 
</script>

输出:

TypeError: Assignment to constant variable.

示例2: 下面的语句也会显示”语法错误”,因为const变量的值只能在声明时定义。

Javascript

// Will throw syntax error as 
// no value has been assigned         
const MY_VAR;

输出:

SyntaxError: Missing initializer in const declaration

示例3:

下面的语句也会抛出一个错误,因为我们尝试声明一个已经被声明为常量的变量名。

Javascript

// Declaring multiple const values 
// with the same variable 
const pi = 3.15; 
const pi = 2.6;

输出结果:

SyntaxError: Identifier 'pi' has already been declared

声明带对象的常量: 通过将对象声明为常量,我们可以操纵对象的内部属性。

示例4:

Javascript

const pair = {x:30, y:60}; 
  
// Updating the x and y values 
// of the object 
pair.x = 10; 
pair.y = 90; 
  
console.log(pair);

输出:

{
  x: 10,
  y: 90
}

常量对象的属性值可以被修改,但是不能重新赋值给常量对象,如下面的示例所示。

示例5:

Javascript

const pair = { x: 30, y: 20 } 
  
// Will throw an error that 
// pair has already been declared 
const pair = { a: 35 }

输出:

SyntaxError: Identifier 'pair' has already been declared

示例 6: 也可以向const对象添加新属性,如下所示。

JavaScript

const pair = { x: 30, y: 20 } 
  
// Adding a new property 
// to the pair 
pair.z = 67; 
  
console.log(pair);

输出结果可能会像这样:

{
  x: 30,
  y: 20,
  z: 67
}

循环中的常量: ES6支持在for-of循环中使用const,在每次迭代中创建新的绑定。

示例7:

JavaScript

const arr = ['hi', 'how', 'are', 'you']; 
  
// Looping through all the elements 
// of the array 
for (const ele of arr) { 
    console.log(ele); 
}

输出:

hi
how
are
you

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程