2020-10-06 23:10:08 +05:30

2.1 KiB
Raw Blame History

id, challengeType, forumTopicId, title
id challengeType forumTopicId title
587d7b7a367417b2b2512b12 1 301158 使用 slice() 拷贝数组项目

Description

接下来我们要介绍slice()方法。slice()并不修改数组,而是复制或者说提取extract给定数量的元素到一个新数组里,而调用方法的数组则保持不变。slice()只接受 2 个输入参数—第一个是开始提取元素的位置索引第二个是结束提取元素的位置索引。slice 方法会提取直到截止索引的元素,但被提取的元素不包括截止索引对应的元素。请看以下例子:
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];

let todaysWeather = weatherConditions.slice(1, 3);
// todaysWeather 等于 ['snow', 'sleet'];
// 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']);
  - text: <code>forecast</code>函数应该使用<code>slice()</code>方法
    testString: assert(/\.slice\(/.test(code));

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

function forecast(arr) {
  return arr.slice(2,4);
}