iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 11
0
自我挑戰組

利用30分鐘~想一個前端問題系列 第 11

利用30分鐘~想一個前端問題 Day11-nthElement

nthElement

Returns the nth element of an array.

Use Array.prototype.slice() to get an array containing the nth element at the first place.
If the index is out of bounds, return undefined.
Omit the second argument, n, to get the first element of the array.

返回陣列的 第n個元素

用 Array.prototype.slice() 拿到 包含第n個元素的陣列 陣列長度為1,如果超出陣列範圍 會返回一個[] 如果省略參數n 會默認獲取第一個元素

const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];
EXAMPLES
nthElement(['a', 'b', 'c'], 1); // 'b'
nthElement(['a', 'b', 'b'], -3); // 'a'

記憶點:

1.slice()

slice() 方法可以任意截取出陣列的一部分

  • 參數 begin 表示開始擷取的索引位置 (索引值從 0 開始),預設是 0
  • 參數 end 表示結束擷取的索引位置,擷取的範圍不包含 end 元素;如果 end 是負數,表示從陣列後面算起,例如 -1 表示最後一個元素的位置
  • slice() 方法返回一個新的陣列

對象:
可操控Array及String

let languages = ["JavaScript", "Python", "C", "C++", "Java"];

//可以淺拷貝
let new_arr = languages.slice();
console.log(new_arr); // [ 'JavaScript', 'Python', 'C', 'C++', 'Java' ]


let new_arr1 = languages.slice(2);
console.log(new_arr1); // [ 'C', 'C++', 'Java' ]

// slicing from the second element to fourth element
let new_arr2 = languages.slice(1, 4);
console.log(new_arr2); // [ 'Python', 'C', 'C++' ]

可使用負數索引,表示由陣列的最末項開始提取。slice(-2) 代表拷貝陣列中的最後兩個元素。

[ 'JavaScript', 'Python', 'C', 'C++', 'Java' ]
[ 'C', 'C++', 'Java' ]
[ 'Python', 'C', 'C++' ]

參考資料

MDN-Array.prototype.slice()


上一篇
利用30分鐘~想一個前端問題 Day10--maxDate
下一篇
利用30分鐘~想一個前端問題 Day12-objectToPairs
系列文
利用30分鐘~想一個前端問題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言