js 中 const 定义的值是否能更改
发布日期:2021-05-04 12:34:15 浏览次数:25 分类:原创文章

本文共 1876 字,大约阅读时间需要 6 分钟。

js 中 const 定义的值是否能更改


验证例子:

使用const定义js基本类型 String

const str = "Clig";str = "lgc";console.log(str); // Clig
VM1568:2 Uncaught TypeError: Assignment to constant variable.    at <anonymous>:2:5

VM1568:2未捕获类型错误:分配给常量变量。
未知:2:5

使用const定义js基本类型 Number

const number = 6;number = 8;console.log(number); // 6
VM1568:2 Uncaught TypeError: Assignment to constant variable.    at <anonymous>:2:8

VM1568:2未捕获类型错误:分配给常量变量。
未知:2:8

使用const定义js基本类型 Boolean

const boolean = true;boolean = false;console.log(boolean); // true
VM1568:2 Uncaught TypeError: Assignment to constant variable.    at <anonymous>:2:9

VM1568:2未捕获类型错误:分配给常量变量。
未知:2:9

使用const定义js基本类型 Null

const n = null;n = 0;console.log(n); // null
VM1568:2 Uncaught TypeError: Assignment to constant variable.    at <anonymous>:2:3

VM1568:2未捕获类型错误:分配给常量变量。
未知:2:3

使用const定义js基本类型 Undefined

const u = undefined;u = 0;console.log(u); // undefined
VM1568:2 Uncaught TypeError: Assignment to constant variable.    at <anonymous>:2:3

VM1568:2未捕获类型错误:分配给常量变量。
未知:2:3

使用const定义js引用类型 Array

const arr = ["李广程",21];arr[2] = "深圳";console.log(arr); // ["李广程", 21, "深圳"]

修改成功

使用const定义js引用类型 Object

const object = {   name:"李广程",age:21};object["address"] = "深圳";console.log(object); // {name: "李广程", age: 21, address: "深圳"}

修改成功

使用const定义js引用类型 Function

const fun = ()=>{   	return "我是引用类型 Function";};fun = () =>{   	return "我是修改后的引用类型 Function";};console.log(fun); // {name: "李广程", age: 21, address: "深圳"}
Uncaught TypeError: Assignment to constant variable.    at <anonymous>:4:5

VM1568:2未捕获类型错误:分配给常量变量。
未知:4:5

使用const定义js引用类型 Date

const date = new Date();date = new Date();console.log(date); // Sun Jan 24 2021 15:43:13 GMT+0800 (中国标准时间)
VM459:2 Uncaught TypeError: Assignment to constant variable.    at <anonymous>:2:6

VM1568:2未捕获类型错误:分配给常量变量。
未知:2:6

结论:const定义的基本类型不能改变,但是定义的引用类型中的 数组对象 可以通过修改对象属性改变。

const使用建议:不要使用const定义 数组对象 作为常量。

上一篇:封装localStorage
下一篇:深拷贝和浅拷贝的区别

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年03月23日 15时31分08秒