freeCodeCamp/guide/chinese/certifications/javascript-algorithms-and-d.../es6/declare-a-read-only-variabl.../index.md

3.7 KiB
Raw Blame History

title localeTitle
Declare a Read-Only Variable with the const Keyword 使用const关键字声明只读变量

:triangular_flag_on_post:如果卡住,请记得使用**Read-Search-Ask** 。尝试配对程序:busts_in_silhouette:并编写自己的代码:pencil:

问题说明:

将所有变量更改为letconst并重命名sentence

:speech_balloon:提示1

  • 用只读const替换var的字符串。

现在尝试解决问题

:speech_balloon:提示1

  • 更换varfor循环来let

现在尝试解决问题

:speech_balloon:提示1

  • 常见的约定是使用ALL CAPS命名const变量。

现在尝试解决问题

扰流警报!

警告牌

提前解决!

:beginner:基本代码解决方案

    function printManyTimes(str) { 
      "use strict"; 
      const SENTENCE = str + " is cool!"; 
      for(let i = 0; i < str.length; i+=2) { 
        console.log(SENTENCE); 
      } 
    } 
    printManyTimes("freeCodeCamp"); 

:rocket: 运行代码

代码说明:

通过在sentence上使用const 我们可以将它设为只读并且通过在for循环中使用let on i ,我们可以避免一起使用var 。为了增加代码清晰度,我们还可以将sentence更改为SENTENCE以显示它是常量。

相关链接

:clipboard:捐款说明:

  • :warning: 请勿添加与任何现有解决方案类似的解决方案。如果您认为它**相似但更好** ,那么尝试合并(或替换)现有的类似解决方案。
  • 添加解决方案的说明。
  • 将解决方案分为以下类别之一 - 基本 中级高级:traffic_light:
  • 如果您添加了任何**相关的主要内容,**请仅添加您的用户名。 :warning: 不要 删除任何现有的用户名

看到:point_right: Wiki Challenge Solution Template供参考。