freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../basic-data-structures/copy-array-items-using-slic...

2.3 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7b7a367417b2b2512b12 Copy Array Items Using slice() 1 使用slice复制数组项

Description

我们将介绍的下一个方法是slice()slice() ,而不是修改数组,将给定数量的元素复制或提取到新数组,而不改变它所调用的数组。 slice()只接受2个参数 - 第一个是开始提取的索引,第二个是停止提取的索引(提取将发生,但不包括此索引处的元素)。考虑一下:
让weatherConditions = ['rain''snow''sleet''hail''clear'];

让todaysWeather = weatherConditions.slice1,3;
//今天天气等于['雪''雨夹雪'];
// weatherConditions仍等于['rain''snow''sleet''hail''clear']
实际上,我们通过从现有数组中提取元素来创建一个新数组。

Instructions

我们定义了一个以数组作为参数的函数forecast 。使用slice()修改函数以从参数数组中提取信息,并返回包含元素'warm''sunny'的新数组。

Tests

tests:
  - text: '<code>forecast</code>应该返回<code>[&quot;warm&quot;, &quot;sunny&quot;]</code>'
    testString: 'assert.deepEqual(forecast(["cold", "rainy", "warm", "sunny", "cool", "thunderstorms"]), ["warm", "sunny"], "<code>forecast</code> should return <code>["warm", "sunny"]");'
  - text: <code>forecast</code>函数应该使用<code>slice()</code>方法
    testString: 'assert(/\.slice\(/.test(code), "The <code>forecast</code> function should utilize the <code>slice()</code> method");'

Challenge Seed

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

  return arr;
}

// do not change code below this line
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));

Solution

// solution required