freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../es6/declare-a-read-only-variabl...

2.8 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7b87367417b2b2512b41 Declare a Read-Only Variable with the const Keyword 1 使用const关键字声明只读变量

Description

let不是声明变量的唯一新方法。在ES6中您还可以使用const关键字声明变量。 const拥有所有的真棒功能, let具有,与额外的奖励,使用声明的变量const是只读的。它们是一个常量值,这意味着一旦变量被赋值为const ,就无法重新赋值。
“严格使用”
const FAV_PET =“Cats”;
FAV_PET =“狗”; //返回错误
如您所见,尝试重新分配使用const声明的变量将引发错误。您应该始终使用const关键字命名您不想重新分配的变量。当您意外尝试重新分配一个旨在保持不变的变量时,这会有所帮助。命名常量时的常见做法是使用全部大写字母,单词用下划线分隔。

Instructions

更改代码,以便使用letconst声明所有变量。如果希望变量更改,请使用let ;如果希望变量保持不变,请使用const 。此外,重命名用const声明的变量以符合常规做法,这意味着常量应该全部大写。

Tests

tests:
  - text: <code>var</code>在您的代码中不存在。
    testString: 'getUserInput => assert(!getUserInput("index").match(/var/g),"<code>var</code> does not exist in your code.");'
  - text: <code>SENTENCE</code>应该是用<code>const</code>声明的常量变量。
    testString: 'getUserInput => assert(getUserInput("index").match(/(const SENTENCE)/g), "<code>SENTENCE</code> should be a constant variable declared with <code>const</code>.");'
  - text: <code>i</code>应该以<code>let</code>来宣布。
    testString: 'getUserInput => assert(getUserInput("index").match(/(let i)/g), "<code>i</code> should be declared with <code>let</code>.");'
  - text: 应更改<code>console.log</code>以打印<code>SENTENCE</code>变量。
    testString: 'getUserInput => assert(getUserInput("index").match(/console\.log\(\s*SENTENCE\s*\)\s*;?/g), "<code>console.log</code> should be adjusted to print the variable <code>SENTENCE</code>.");'

Challenge Seed

function printManyTimes(str) {
  "use strict";

  // change code below this line

  var sentence = str + " is cool!";
  for(var i = 0; i < str.length; i+=2) {
    console.log(sentence);
  }

  // change code above this line

}
printManyTimes("freeCodeCamp");

Solution

// solution required