JS : More Array Methods
const array1 = ;const firstElement = array1.shift();
console.log(array1);
// expected output: Array
console.log(firstElement);
// expected output: 1用 .shift() 方法移除第一個 element.
let arr = ;
arr.unshift(1, 2, 3);
console.log(arr);
//
用 .unshift() 方法在 array 前面加上 elements.
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 開始算起。
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() 方法
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]