Files
Nicholas Carrigan (he/him) 3da4be21bb chore: seed chinese traditional (#42005)
Seeds the chinese traditional files manually so we can deploy to
staging.
2021-05-05 22:43:49 +05:30

1.8 KiB
Raw Permalink Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
587d7b7a367417b2b2512b12 使用 slice() 複製數組元素 1 301158 copy-array-items-using-slice

--description--

接下來我們要介紹 slice() 方法。 slice() 不會修改數組,而是會複製,或者說*提取extract*給定數量的元素到一個新數組。 slice() 只接收 2 個輸入參數:第一個是開始提取元素的位置(索引),第二個是提取元素的結束位置(索引)。 提取的元素中不包括第二個參數所對應的元素。 如下示例:

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() 從輸入的數組中提取信息,最終返回一個包含元素 warmsunny 的新數組。

--hints--

forecast 應返回 ["warm", "sunny"]

assert.deepEqual(
  forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']),
  ['warm', 'sunny']
);

forecast 函數中應使用 slice() 方法。

assert(/\.slice\(/.test(code));

--seed--

--seed-contents--

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

  return arr;
}

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

--solutions--

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