陣列的遍歷

2021-10-01 16:41:38 字數 991 閱讀 7809

陣列的遍歷

1.1 for…of 迴圈

for(const item of items)迴圈遍歷陣列項,如下所示遍歷colors列表:

const colors =

['blue', 'green', 'white'];

for(const color of colors)

// 'blue'

// 'green'

// 'white'

for(let i; i < array.length; i++)迴圈使用遞增的索引變數遍歷陣列項。

for通常需要在每個迴圈中遞增index 變數

const colors =

['blue', 'green', 'white'];

for(let index = 0; index < colors.length; index++)

// 'blue'

// 'green'

// 'white'

index變數從0遞增到colors.length-1。此變數用於按以下索引訪問項:colors [index]。

提示

咱們可以隨時使用break語句停止遍歷。

1.3 array.foreach() 方法

array.foreach(callback)方法通過在每個陣列項上呼叫callback函式來遍歷陣列項。

在每次遍歷中,都使用以下引數呼叫callback(item [, index [, array]]):當前遍歷項,當前遍歷索引和陣列本身。

const colors =

['blue', 'green', 'white'];

colors.foreach(function callback(value, index));

// 'blue', 0

// 'green', 1

// 'white', 2

陣列的遍歷

從頭遍歷元素在陣列中的位置,如果沒有找到則返回 1 var arr hao hi hello nihao nice var str arr.indexof nihao console.log str 3 從末尾遍歷元素在陣列中的位置,如果沒有找到則返回 1 var arr hao hi hello ...

PERL陣列的遍歷

在雙引號內可以使用 直接輸出陣列 rocks qw flinstone slate rubblke print quarrz rocks limtstone n print fred rocks.com.cn 如果我們真的想要輸出 21136.com.cn,那麼我們需要將 轉義,即 或者直接使用單引...

PHP陣列的遍歷

用for迴圈對索引陣列進行遍歷 定義乙個陣列 arr array aa bb cc dd 求得陣列的長度 len count arr 用for迴圈遍歷 for i 0 i len i 用for迴圈對關聯陣列進行遍歷 定義乙個陣列 arr array 姓名 小強 年齡 21 性別 男 求得陣列單元數 ...