freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../basic-data-structures/add-items-using-splice.chin...

3.4 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d78b3367417b2b2512b11 Add Items Using splice() 1 使用splice添加项目

Description

还记得在上一次挑战中我们提到过splice()最多需要三个参数吗?好吧,我们可以更进一步使用splice() - 除了删除元素之外,我们还可以使用代表一个或多个元素的第三个参数来添加它们。这对于快速切换另一个元素或一组元素非常有用。例如假设您正在为数组中的一组DOM元素存储颜色方案并希望根据某些操作动态更改颜色
function colorChangearrindexnewColor{
arr.spliceindex1newColor;
返回
}

让colorScheme = ['878787''a08794''bb7e8c''c9b6be''d1becf'];

colorScheme = colorChangecolorScheme2'332327';
//我们删除了'bb7e8c'并在其位置添加了'332327'
// colorScheme现在等于['878787''a08794''332327''c9b6be''d1becf']
此函数采用十六进制值数组,删除元素的索引以及用于替换已删除元素的新颜色。返回值是一个包含新修改的颜色方案的数组!虽然这个例子有点过于简单,但我们可以看到利用splice()到其最大潜力的值。

Instructions

我们定义了一个函数htmlColorNames 它将一组HTML颜色作为参数。使用splice()修改函数以删除数组的前两个元素,并在各自的位置添加'DarkSalmon''BlanchedAlmond' 'DarkSalmon'

Tests

tests:
  - text: '<code>htmlColorNames</code>应该返回<code>[&quot;DarkSalmon&quot;, &quot;BlanchedAlmond&quot;, &quot;LavenderBlush&quot;, &quot;PaleTurqoise&quot;, &quot;FireBrick&quot;]</code>'
    testString: 'assert.deepEqual(htmlColorNames(["DarkGoldenRod", "WhiteSmoke", "LavenderBlush", "PaleTurqoise", "FireBrick"]), ["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"], "<code>htmlColorNames</code> should return <code>["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"]</code>");'
  - text: <code>htmlColorNames</code>函数应该使用<code>splice()</code>方法
    testString: 'assert(/.splice/.test(code), "The <code>htmlColorNames</code> function should utilize the <code>splice()</code> method");'
  - text: 你不应该使用<code>shift()</code>或<code>unshift()</code> 。
    testString: 'assert(!/shift|unshift/.test(code), "You should not use <code>shift()</code> or <code>unshift()</code>.");'
  - text: 您不应该使用数组括号表示法。
    testString: 'assert(!/\[\d\]\s*=/.test(code), "You should not use array bracket notation.");'

Challenge Seed

function htmlColorNames(arr) {
  // change code below this line

  // change code above this line
  return arr;
}

// do not change code below this line
console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurqoise', 'FireBrick']));

Solution

// solution required