標籤:刪除 array 返回 start 刪除元素 rip header rom ...
集合Array
2種建立數組的方式
var fruits = [] ;
var friuits = new Array();
遍曆
fruits.forEach(function (item, index, array){
console.log(item, index);
});
// Apple 0
// Banana 1
基本操作
操作 |
代碼 |
傳回值 |
添加元素到數組的末尾 |
fruits.push(‘Orange‘) |
數組長度 |
添加元素到數組的頭部 |
fruits.unshift(‘Strawberry‘) |
數組長度 |
刪除頭部元素 |
fruits.shift(); |
頭部元素 |
刪除尾部元素 |
fruits.pop(); |
尾部元素 |
找出某個元素在數組中的索引 |
fruits.indexOf(‘Banana‘); |
下標 |
通過索引刪除某個元素 |
fruits.splice(index, 1); |
被刪除的元素 |
複製數組 |
var shallowCopy = fruits.slice(0,length); |
返回指定範圍內元素組成的新數組 |
產生數組 |
Array.from() |
Array.from() 方法從一個類似數組或可迭代對象中建立一個新的數組執行個體。 |
根據索引刪除元素的例子
/* splice(start: number, deleteCount: number, ...items: T[]): T[]; */
var fruits = ["apple","b","c","d"] ;
console.log("array is : ");
fruits.forEach(function (item, index, array){
console.log(item, index);
});
var index = fruits.indexOf("b");
fruits.splice(index,1);
console.log("array is : ");
fruits.forEach(function (item, index, array){
console.log(item, index);
});
Array.from()使用例子
var fruits = ["apple","b","c","d"] ;
var f = Array.from(fruits);
f.forEach(function (item, index, array){
console.log(item, index);
});
//apple 0
//b 1
//c 2
//d 3
var f = Array.from("hello");
f.forEach(function (item, index, array){
console.log(item, index);
});
//h
//e
//l
//l
//o
Array.from()還可以用於Set,Map
SetMap
JavaScript 進階(未完待續)