〖學習筆記〗JavaScript — 陣列相關方法

Shih Ting, Tai
13 min readSep 29, 2021

indexOf 搜尋索引值

它可以給定一個要在陣列中搜尋的成員(值),如果找到的話就會回傳成員的索引值,沒找到就會回傳 -1數字。多個成員符合的話,它只會回傳最先找到的那個(一律是從左至右),它的比對是使用完全符合的比較運算符 ===

可加入第二個參數(可選擇的),它是「開始搜尋的索引值」,如果是負整數則從最後面倒過來計算位置的(最後一個索引值相當於-1)。

const aArray = ['a', 'b', 'c', 'a', 'c', 'c']console.log(aArray.indexOf('a')) //0
console.log(aArray.indexOf('c')) //2
console.log(aArray.indexOf('c', 3)) //4
console.log(aArray.indexOf('a', -3)) //3,-3代表要從索引值3開始搜尋

concat 串聯

用於合併其他陣列或值,到一個陣列上的方法。它最後會回傳一個新的陣列。

array.concat(value1[, value2[, …[, valueN]]])

它與展開運算符可以互為替代:

const strArray = ['a', 'b', 'c']
const numArray = [1, 2, 3]
const aString = 'Hello'
const newArray = strArray.concat(numArray)
console.log(newArray) // ['a', 'b', 'c', 1, 2, 3]
// * 連鎖(chain)運算
const newArray1 = strArray.concat(numArray).concat(aString)
console.log(newArray1) // ['a', 'b', 'c', 1, 2, 3, 'Hello']
// * 展開運算符(相同的作法)
const newArray2 = [...strArray, ...numArray]
console.log(newArray2) // ['a', 'b', 'c', 1, 2, 3]
注意: 陣列沒有運算符這種東西。但是字串類型可以用合併運算符(+),或是用同名方法concat作合併。

slice 分割

是用於分割出子陣列的方法,它會用淺拷貝(shallow copy)的方式,回傳一個新的陣列。這個方法與字串中的分割子字串所使用的的同名稱方法slice,類似的作法。

array.slice(start[, end])

使用陣列的索引值作為前後參數,複製開始與結束點(結束點不算)

  • 當開頭索引值為undefined時(空白沒寫),它會以0計算,也就是陣列最開頭。
  • 當索引值有負值的情況下,它是從最後面倒過來計算位置的(最後一個索引值相當於-1 )
  • 只要遵守「開頭索引值」比「結束索引值」的位置更靠左,就有回傳值。
  • slice(0)相當於陣列淺拷貝
const aArray = [1, 2, 3, 4, 5, 6]const bArray = aArray.slice(1, 3) // [2, 3]
const cArray = aArray.slice(0) // [1, 2, 3, 4, 5, 6]
const dArray = aArray.slice(-1, -3) // []
const eArray = aArray.slice(-3, -1) // [4, 5]
const fArray = aArray.slice(1, -3) // [2, 3]

splice 黏貼

用於刪除或增加陣列中的成員。在陣列的中間「插入」幾個新的成員(值),或是「刪掉」其中的幾個成員(值)用的。

array.splice(start, deleteCount[, item1[, item2[, …]]])

方法的參數值:

  • start :是開始要作這件事的索引值,左邊從0開始,如果是負數則從右邊(最後一個)開始計算
  • deleteCount :是要刪除幾個成員(值),最少為0代表不刪除成員(值)
  • item1… :這是要加進來的成員(值),不給這些成員(值)的話,就只會作刪除的工作,不會新增成員(值)。注意如果是陣列值,會變成巢狀(子)陣列成員(值)。

常用的幾個範例:

  • 插入一個新成員(值)在某個值之後

插入某個值之後需要先找出這個某個值的索引值,所以會用indexOf來找。若要在「某個值」的後面插入新成員(值),「後面」代表新成員(值)的索引值還需要加1才行:

const dictionary = ['a', 'b', 'd']// 先找到b的位置,等會要在b後面插入c
const bIndex = dictionary.indexOf('b')
// bIndex大於-1代表有存在,不刪除,插入c
if (bIndex > -1) {
dictionary.splice(bIndex+1, 0, 'c') // ['a', 'b', 'c', 'd']
}
  • 用新成員(值)取代某個值
const dictionary = ['a', 'b', 'x', 'd']// 先找到x的位置,等會要用c來取代x
const xIndex = dictionary.indexOf('x')
// bIndex大於-1代表有存在,刪除x,插入c
if (bIndex > -1) {
dictionary.splice(xIndex, 1, 'c') // ['a', 'b', 'c', 'd']
}
  • 用於刪除成員(值)

多個值的情況,用迴圈語句:

const dictionary = ['x', 'b', 'x', 'x', 'b']for (let i = 0, len = dictionary.length; i < len; i++){    // 大於-1代表有存在,刪除x
if (dictionary[i] === 'x'){
dictionary.splice(i, 1) // ['b', 'b']
}
}

陣列與字串 join(結合) 與split (分離)

join(結合) 是陣列的方法:

用途是把陣列中的成員(值)組合為一個字串,組合的時候可以加入組合時用的分隔符號(或空白字元)。

const aArray = ['Hello', 'Hi', 'Hey']
const aString = aArray.join() //Hello,Hi,Hey
const bString = aArray.join(', ') //Hello, Hi, Hey
const cString = aArray.join('') //HelloHiHey

split(分離)是字串中的方法:

把字串拆解成陣列的成員,拆解時需要給定一個拆解基準的符號(或空白),通常是用逗號(,)分隔,以下為範例:

const monthString = 'Jan,Feb,Mar,Apr,May'
const monthArray1 = monthString.split(',') //["Jan", "Feb", "Mar", "Apr", "May"]
//以下為錯誤示範
const monthArray2 = monthString.split() //["Jan,Feb,Mar,Apr,May"]
const monthArray3 = monthString.split('') //["J", "a", "n", ",", "F", "e", "b", ",", "M", "a", "r",

以下方法的範例都是使用同一份陣列資料:

// 相同的陣列
var people = [
{
name: 'Casper',
like: '鍋燒意麵',
age: 18
},
{
name: 'Wang',
like: '炒麵',
age: 24
},
{
name: 'Bobo',
like: '蘿蔔泥',
age: 1
},
{
name: '滷蛋',
like: '蘿蔔泥',
age: 3
}
];

filter() 過濾

會回傳一個陣列,其條件是 return 後方為 true 的物件,很適合用在搜尋符合條件的資料。

var filterEmpty = people.filter(function(item, index, array){
});
console.log(filterEmpty); // 沒有條件,會是一個空陣列
var filterAgeThan5 = people.filter(function(item, index, array){
return item.age > 5; // 取得大於五歲的
});
console.log(filterAgeThan5); // Casper, Wang 這兩個物件
var filterDouble = people.filter(function(item, index, array){
return index % 2 === 1; // 取得陣列中雙數的物件
});
console.log(filterDouble); // Wang, 滷蛋 這兩個物件

find() 搜尋

find() 與 filter() 很像,但 find() 只會回傳一次值,且是第一次為 true 的值。

var findEmpty = people.find(function(item, index, array){
});
console.log(findEmpty); // 沒有條件,會是 undefined
var findAgeThan5 = people.find(function(item, index, array){
return item.age > 5; // 取得大於五歲的
});
console.log(findAgeThan5); // 雖然答案有兩個,但只會回傳 Casper 這一個物件
var findLike = people.find(function(item, index, array){
return item.like === '蘿蔔泥'; // 取得陣列 like === '蘿蔔泥'
});
console.log(findLike); // 雖然答案有兩個,但只會回傳第一個 Bobo 物件

forEach()

forEach 是這幾個陣列函式最單純的一個,不會額外回傳值,只單純執行每個陣列內的物件或值。

var forEachIt = people.forEach(function(item, index, array){
console.log(item, index, array); // 物件, 索引, 全部陣列
return item; // forEach 沒在 return 的,所以這邊寫了也沒用
});
console.log(forEachIt); // undefined
people.forEach(function(item, index, array){
item.age = item.age + 1; // forEach 就如同 for,不過寫法更容易
});
console.log(people); // 全部 age + 1

map() 映射

使用 map() 時他需要回傳一個值,他會透過函式內所回傳的值組合成一個陣列。

  • 如果不回傳則是 undefined
  • 回傳數量等於原始陣列的長度

這很適合將原始的變數運算後重新組合一個新的陣列。

var mapEmpty = people.map(function(item, index, array){
});
console.log(mapEmpty); // [undefined, undefined, undefined, undefined]
var mapAgeThan5 = people.map(function(item, index, array){
return item.age > 5; // 比較大於五歲的
});
console.log(mapAgeThan5); // [true, true, false, false]
var mapAgeThan5_2 = people.map(function(item, index, array){
// 錯誤示範
if (item.age > 5) {
return item; // 回傳大於五歲的
}
return false; // 別以為空的或是 false 就不會回傳
});
console.log(mapAgeThan5_2); // [{name: 'Casper'...}, {name: 'Wang'...}, false, false]var mapEat = people.map(function(item, index, array){
if (item.like !== '蘿蔔泥') {
return `${item.like} 好吃`;
} else {
return `${item.like} 不好吃`;
}
});
console.log(mapEat); // ["鍋燒意麵 好吃", "炒麵 好吃", "蘿蔔泥 不好吃", "蘿蔔泥 不好吃"]

reduce() 歸納

他可以與前一個回傳的值再次作運算,參數包含以下:

  • accumulator: 前一個參數,如果是第一個陣列的話,值是以另外傳入或初始化的值
  • currentValue: 當前變數
  • currentIndex: 當前索引
  • array: 全部陣列
// * 沒有條件,會是 undefined
var
reduceEmpty = people.reduce(function(accumulator, currentValue, currentIndex, array){
});
console.log(reduceEmpty); // undefined
// * 與前一個值相加
var reducePlus = people.reduce(function(accumulator, currentValue, currentIndex, array){
// 分別為前一個回傳值, 目前值, 當前索引值
console.log(accumulator, currentValue, currentIndex);
return accumulator + currentValue.age; // 與前一個值相加
}, 0); // 傳入初始化值為 0
console.log(reducePlus); // 46

//
* 與前一個值比較哪個大
var reducePlus = people.reduce(function(accumulator, currentValue, currentIndex, array){
console.log('reduce', accumulator, currentValue, currentIndex)
return Math.max( accumulator, currentValue.age ); // 與前一個值比較哪個大
}, 0);
console.log(reducePlus); // 24

參考資料:

--

--

Shih Ting, Tai

Enhance overall happiness by improving human-computer interaction to benefit people.