JavaScript中的const

const (const)

Like other programming languages, JavaScript also provide the feature to create constants, we can make any identifier as constant by using the "const".

与其他编程语言一样,JavaScript也提供了创建常量的功能,我们可以使用“ const”将任何标识符设为常量。

"const" is a keyword in JavaScript and it makes an identifier constant.

“ const”是JavaScript中的关键字,它使标识符恒定。

Syntax:

句法:

const identifier_name = value;

Points to remember:

要记住的要点:

  • While creating a constant, a value should be assigned.

    创建常数时,应分配一个值。

  • A constant’s value cannot be changed.

    常量的值不能更改。

Error

错误

If we try to change the value of a constant following type error throws:

如果我们尝试更改以下常量的值,则会引发类型错误:

TypeError: Assignment to constant variable.

Example:

例:

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>		
		const url = "www.example.com";
		const port_no = 25;
		
		//printing...
		document.write("url: " + url + "<br>");
		document.write("port_no: " + port_no + "<br>");
		
		//if you will try to change the value
		//it will not be changed
		try{
		port_no = 21;		
		}
		catch(err){
			document.write(err + "<br>");
		}
	</script>
</body>
</html>

Output

输出量

url: www.example.com
port_no: 25
TypeError: Assignment to constant variable.


翻译自: https://www.includehelp.com/code-snippets/const-in-javascript.aspx

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值