JavaScript數組_數組方法【二】(二十七)

目錄:

1.數組方法【二】數組

1、數組方法

  • indexOf()和 lastIndexOf() (ES5新增)
  • forEach() (ES5新增)
  • map() (ES5新增)
  • filter() (ES5新增)
  • every() (ES5新增)
  • some() (ES5新增)

一、indexOfbash

Array.prototype.indexOf(searchElement[, fromIndex = 0]) 返回在數組中找到給定元素的第一個索引,若是不存在,則返回-1。
searchElement 須要查找的元素。
fromIndex 開始查找的位置。
// 建立數組
var arr = ['妲己', '小狐狸', 16, 'girl', '古箏','妲己', '小狐狸', 16, 'girl', '古箏']
// 獲取數組的下標
var index  = arr.indexOf('小狐狸')
console.log(index) // 結果爲: 1
console.log(arr.indexOf('小狐狸', 4)) // 結果爲:6複製代碼

二、lastIndexOfmarkdown

Array.prototype.lastIndexOf(searchElement[, fromIndex = arr.length - 1]) 獲取指定元素在數組中的最後一個的索引,若是不存在則返回 -1。從數組的後面向前查找。
searchElement 須要查找的元素。
formIndex 今後位置開始逆向查找。默認爲數組的長度減 1。
var arr = ['妲己', '小狐狸', 16, 'girl', '古箏','妲己', '小狐狸', 16, 'girl', '古箏']
var index = arr.lastIndexOf('girl')
console.log(index) // 結果爲:8
console.log(arr.lastIndexOf('girl', 7)) // 結果爲:3複製代碼

三、forEach函數

Array.prototype.forEach(callback[, thisArg]) 調用數組的每一個元素,並將元素傳遞給回調函數(callback)。
callback 爲數組中每一個元素執行的函數,該函數接收三個參數:
currentValue 正在處理的當前元素(第一個參數)
index 正在處理的當前元素的索引(第二個參數)
array 正在操做的數組(第三個參數)
thisArg 當執行回調函數時用做 this 的值
返回值:undefined
var arr = ['妲己', '小狐狸', 16, 'girl', '古箏']
arr.forEach(function (item, index, arr) {
    console.log('索引爲:'+index+',元素爲:'+item, arr)
})
------執行結果-------
索引爲:0,元素爲:妲己 ["妲己", "小狐狸", 16, "girl", "古箏"]
索引爲:1,元素爲:小狐狸 ["妲己", "小狐狸", 16, "girl", "古箏"]
索引爲:2,元素爲:16 ["妲己", "小狐狸", 16, "girl", "古箏"]
索引爲:3,元素爲:girl ["妲己", "小狐狸", 16, "girl", "古箏"]
索引爲:4,元素爲:古箏 ["妲己", "小狐狸", 16, "girl", "古箏"]複製代碼

四、mapoop

Array.prototype.map(callback[, thisArg]) 遍歷數組中的元素,經過回調函數加工;加工後返回一個新數組,數組中的元素爲原始數組元素調用函數處理後的值。
參數同 Array.prototype.forEach()
var arr = ['妲己', '小狐狸', 16, 'girl', '古箏']
// 接收加工後的新數組
var newArr = arr.map(function (item, index, arr) {
    return item + index
})
console.log(newArr)

------------------------------執行結果------------------------------
["妲己0", "小狐狸1", 18, "girl3", "古箏4"]複製代碼

五、filterthis

Array.prototype.filter(callback(element[, index[, array]])[, thisArg]) 返回一個新的數組,新數組中的元素是經過檢查指定數組中符合條件的全部元素。
參數同上
var arr = [12,54,5,3,165,46,5,48,56,4,7,5,79,4,5,94,65,87]
// 使用變量 newArr 保存返回的數組
var newArr = arr.filter(function (item, index) {
    return item>20
})
console.log(newArr)

------------------------------執行結果------------------------------
[54, 165, 46, 48, 56, 79, 94, 65, 87]複製代碼

六、everyspa

該方法對數組中的每一項運行給定函數,若是該函數對每一項都返回 true,則返回true。
var arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.every( function( item, index, array ){  
    console.log( 'item=' + item + ',index='+index+',array='+array );  
    return item > 3;  
})); 複製代碼

七、someprototype

該方法對數組中的每一項運行給定函數,若是該函數對任何一項返回 true,則返回true。
var arr = [ 1, 2, 3, 4, 5, 6 ];  

console.log( arr.some( function( item, index, array ){  
    console.log( 'item=' + item + ',index='+index+',array='+array );  
    return item > 3;  
}));  複製代碼

下節預告:數組_冒泡排序

參考視頻教程:zhuanlan.zhihu.com/p/95909716

相關文章
相關標籤/搜索