Vue必學知識點之forEach()的使用
在前端開發中,經常會遇到一些通過遍歷循環來獲取想要的內容的情形,而且這種情形在開發中無所不在,那么本篇博文就來分享一個比較常用又經典的知識點:forEach() 的使用。
forEach() 是前端開發中操作數組的一種方法,主要功能是遍歷數組,其實就是 for 循環的升級版,該語句需要有一個回調函數作為參數。回調函數的形參依次為:1、value:遍歷數組的內容;2、index:對應數組的索引,3、array:數組自身。
在 Vue 項目中,標簽里的循環使用 v-for,方法里面的循環使用 forEach。
一、forEach() 使用原理forEach() 方法主要是用于調用數組的每個元素,并將元素傳遞給回調函數。需要注意的是: forEach() 方法對于空數組是不會執行回調函數的。
forEach:即 Array.prototype.forEach,只有數組才有的方法,相當于 for 循環遍歷數組。用法:arr.forEach(function(item,index,array){...}),其中回調函數有 3 個參數,item 為當前遍歷到的元素,index 為當前遍歷到的元素下標,array 為數組本身。forEach 方法不會跳過 null 和 undefined 元素。比如數組[1,undefine,null,,2]中的四個元素都將被遍歷到,注意與 map 的區別。
二、forEach() 語法array.forEach(function(currentValue, index, array), thisValue)
例子:
array.forEach(function(item,index,array){ ... })
三、forEach() 其他相關內容1、forEach()的 continue 和 break:
forEach() 自身不支持 continue 和 break 語句的,但是可以通過 some 和 every 來實現。
2、forEach()與 map 的區別:
forEach()沒有返回值,性質上等同于 for 循環,對每一項都執行 function 函數。即 map 是返回一個新數組,原數組不變,而 forEach 是改變原數組。
3、forEach()與 for 循環的對比:
for 循環步驟多比較復雜,forEach 循環比較簡單好用,不易出錯。
4、forEach()例子:
實例一:
let array = [1, 2, 3, 4, 5, 6, 7];array.forEach(function (item, index) { console.log(item); //輸出數組的每一個元素});
實例二:
var array=[1, 2, 3, 4, 5];array.forEach(function(item, index, array){ array[index]=4 * item;});console.log(array); //輸出結果:修改了原數組元素,為每個元素都乘以4
實例三:
<el-checkbox v-for='(item) in searchContent' :label='item.id' :key='item.id' class='checkbox'> <span>{{item.value}}{{item.checked}}</span> </el-checkbox> handle(index, row) {this.selectedCheck=[];let a = this;this.jurisdiction = true;this.roleId = row.id;this.$http.get(“/user/resources', { params: {userId: this.userId} }).then((response) => { a.searchContent = response.body; a.searchContent.forEach(function (b) { if(b[‘checked’]){ a.selectedCheck.push(b.id); } })})
實例四:
var userList = new Array();var data = {};if (response.data.userList != null && response.data.userList.length > 0) { response.data.userList.forEach((item, index) => { data.a = item.a; data.b = item.b; data.arr1 = new Array(); data.arr1[0] = item.c; data.arr1[1] = item.d; data.e = item.e; data.f = item.f; data.arr2 = new Array(); data.arr2[0] = item.j; data.arr2[1] = item.h; userList.push(data); });}
實例五:
searchDept(keyWord, callback) { if (keyWord) {this.$service.data .searchDepts({ data: { full_name: keyWord } }) .then(r => { if (r.Success) { let arr = []; r.Data.Result.forEach(element => {arr.push({ id: element.work_id, value: element.full_name, dept: element}); }); callback(arr); } }); } },
到此這篇關于Vue必學知識點之forEach()使用的文章就介紹到這了,更多相關Vue forEach()使用內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
