admin 發表於 2022-8-22 13:29:00

JS : More Array Methods

const array1 = ;

const firstElement = array1.shift();

console.log(array1);
// expected output: Array

console.log(firstElement);
// expected output: 1用 .shift() 方法移除第一個 element.

admin 發表於 2022-8-22 13:36:15

let arr = ;

arr.unshift(1, 2, 3);
console.log(arr);
//
用 .unshift() 方法在 array 前面加上 elements.

admin 發表於 2022-8-22 13:45:29

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]slice() 方法:

slice()
slice(start)
slice(start, end) // 不包含 end 那個,只到 end 前一個index 從 0 開始算起。

admin 發表於 2022-8-22 13:58:22

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1indexOf() 方法

admin 發表於 2022-8-22 14:01:49

const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];

groceryList.shift();
groceryList.unshift('popcorn');
console.log(groceryList);
console.log(groceryList.slice(1,4));
console.log(groceryList); // 沒有因為 slice 而改變
const pastaIndex = groceryList.indexOf('pasta');
console.log(pastaIndex);
頁: [1]
查看完整版本: JS : More Array Methods