vue 循环遍历对象、数组和字符串
1.循环遍历对象
1.1vue 在html里面循环遍历对象
v-for=" (val, key , i) in dimItemMap" :key="key"
val-每一项
key -key值
i-第几个
<el-table-column prop="score" label="评分":show-overflow-tooltip="true" align="center"><template slot-scope="scope"><span><span v-for=" (val, key , i) in scope.row.dimItemMap":key="key">{{val.score}}//score为键,val.score为值</span></span></template></el-table-column>
1.2 在js里面forin遍历对象
for…in 循环主要是为了遍历对象而生,不适用于遍历数组
let data=[{wiun2dvi:232,wiun3dvi:55,wiu4ndvi:33,wiun1dvi:24432}];
data.forEach((item,index)=>{for(const keyin item){
console.log("item[key]",item[key]);//值
console.log("key",key);//键}})
2.循环遍历数组
2.1 vue 在html里面循环遍历数组
<el-table-column v-for="item in tableCol":key="item.id":prop="item.id":label="item.name":show-overflow-tooltip="true" align="center"><template slot-scope="scope"><span>{{scope.row.dimItemMap?scope.row.dimItemMap[item.id].name:""}}</span></template></el-table-column>
<el-table-column prop="score" label="评分":show-overflow-tooltip="true" align="center"><template slot-scope="scope"><span><span v-for=" (item, index) in scope.row.dimItemMap":key="index">{{item.score}}</span></span></template></el-table-column>
2.2 在js里面for遍历数组
let id=1524466for(let i=0; i< list.length; i++){let a= list[i];if(a.id=== id){return a.name;}}
2.3 在js里面forof遍历数组
let arr=[{name:12,hello:"wsdfnioq",},{name:12,hello:"wsdfnioq",},{name:12,hello:"wsdfnioq",}]for(const iof arr){
console.log("i", i);}//i {name: 12, hello: 'wsdfnioq'}// i {name: 12, hello: 'wsdfnioq'}//i {name: 12, hello: 'wsdfnioq'}
let arr=[['name',"张三"],['地址','北京'],['手机','123']]for(const[value0, value1]of arr){
console.log('k', value0, value1);}// k name 张三// k 地址 北京// k 手机 123
2.4 forin,不推荐对数组进行遍历
let arr=["lsadnkol","klsmvaod","lpsaojfoas"]for(const keyin arr){
console.log("arr", key,typeof key, arr[key]);}// 0 string lsadnkol// 1 string klsmvaod// 2 string lpsaojfoas
2.4 forEach() 函数遍历数组
①无任何返回,可改变原来数组中的内容
②循环次数:数组的长度
③不支持return,不需要return语句
如下案例:给每个对象中添加age属性
let forArr=[{name:'tom',sex:'man'},{name:'linda',sex:'woman'},]
forArr.forEach((item,index)=>{
console.log("forEach循环==index==",index,item);
item.age=27})
console.log("forArr==遍历后===",forArr)// forArr ---->[{name:'tom',sex:'man',age:27},{name:'linda',sex:'woman',age:27}]
3.循环遍历字符串
3.1for
let s="abcd"for(let i=0; i< s.length; i++){
console.log(i,typeof i, s[i]);//i为索引,s[i]为值,typeof i 为number}// 0 number a// 1 number b// 2 number c// 3 number d
3.2 forin
let s="abcd"for(const keyin s){
console.log("key", key,typeof key, s[key]);//key为索引,s[key]为值,typeof key 为string}// 0 string a// 1 string b// 2 string c// 3 string d
3.3 forof
let s="abcd"for(const iof s){
console.log("i", i);//i为值}// a// b// c// d