freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../es6/mutate-an-array-declared-wi...

2.6 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7b87367417b2b2512b42 Mutate an Array Declared with const 1 改变用const声明的数组

Description

const声明在现代JavaScript中有许多用例。一些开发人员更喜欢默认使用const分配所有变量,除非他们知道需要重新分配值。只有在这种情况下,他们才会使用let 。但是,重要的是要理解使用const分配给变量的对象(包括数组和函数)仍然是可变的。使用const声明仅阻止重新分配变量标识符。
“严格使用”;
const s = [5,6,7];
s = [1,2,3]; //抛出错误尝试分配const
s [2] = 45; //就像使用var或let声明的数组一样工作
的console.log一个或多个; //返回[5,6,45]
如您所见,您可以改变对象[5, 6, 7]本身,变量s仍将指向更改的数组[5, 6, 45] 。与所有数组一样, s中的数组元素是可变的,但由于使用了const ,因此不能使用变量标识符s使用赋值运算符指向不同的数组。

Instructions

数组声明为const s = [5, 7, 2] 。使用各种元素分配将数组更改为[2, 5, 7]

Tests

tests:
  - text: 不要替换<code>const</code>关键字。
    testString: 'getUserInput => assert(getUserInput("index").match(/const/g), "Do not replace <code>const</code> keyword.");'
  - text: <code>s</code>应该是一个常量变量(使用<code>const</code> )。
    testString: 'getUserInput => assert(getUserInput("index").match(/const\s+s/g), "<code>s</code> should be a constant variable (by using <code>const</code>).");'
  - text: 不要更改原始数组声明。
    testString: 'getUserInput => assert(getUserInput("index").match(/const\s+s\s*=\s*\[\s*5\s*,\s*7\s*,\s*2\s*\]\s*;?/g), "Do not change the original array declaration.");'
  - text: '<code>s</code>应该等于<code>[2, 5, 7]</code> 。'
    testString: 'assert.deepEqual(s, [2, 5, 7], "<code>s</code> should be equal to <code>[2, 5, 7]</code>.");'

Challenge Seed

const s = [5, 7, 2];
function editInPlace() {
  "use strict";
  // change code below this line

  // s = [2, 5, 7]; <- this is invalid

  // change code above this line
}
editInPlace();

Solution

// solution required