当前位置:   article > 正文

数组循环及对象循环找key或value_for 循环拿到key

for 循环拿到key

for, forEach, for-in, for-of(es6)

let arr = [1,2,3,4,5];
arr.b = '100'; // 自定义私有属性
  • 1
  • 2
// for循环 速度最快
for (let i = 0; len = arr.length, i < len; i++) { // 编程式
console.log("for循环"+arr[i]);
}
  • 1
  • 2
  • 3
  • 4
// forEach 不支持return和break,无论如何都会遍历完,
arr.forEach(function(item){
console.log("forEach循环"+item);
});
  • 1
  • 2
  • 3
  • 4

Vue 循环map对象拿到key值和value值

适用场景:

vue中定义的map对象 map : { name : 'xxx' }

接口回显map格式的数据 data :{ key : value}

都可以通过以下方式拿到keyvalue的值

// for-in 遍历的是 key 值,且 key 会变成字符串类型,包括数组的私有属性也会打印输出
for(let key in arr){
console.log("for in循环"+key);
console.log(typeof key);
}
  • 1
  • 2
  • 3
  • 4
  • 5
for(const key in map){
console.log("key名称是:"+key+",key的值是:"+map[key])
}
  • 1
  • 2
  • 3
// for-of 遍历的是值 val,只能遍历数组 (不能遍历对象)
for(let val of arr){
console.log("for of循环"+val);
}
  • 1
  • 2
  • 3
  • 4
// Object.keys 将对象的 key 作为新的数组,这样 for-of 循环的就是原数组的 key 值
let obj = {school:'haida',age:20};
// 变成 ['school','age']
for(let val of Object.keys(obj)){
console.log(obj[val]);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

eg:(使用for-in ) 组装下拉框需要的数据格式

接口返回的格式

在这里插入图片描述

    // 获取产线列表
    getLine() {
      linePullDown().then((res) => {
        for (let key in res.data) {
          this.lineOptions.push({
            name: key,
            id: key,
          });
        }
      });
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

组装后数据格式

在这里插入图片描述

页面下拉框 渲染效果

在这里插入图片描述

eg2 循环对象,拿到对应的key及value值,组装成新数组

数据格式

   res:{data:{0011}}
  • 1
 for (let key in res.data) {
     this.expireData.push({
         name: key,
         num: res.data[key],
     });
  }
    this.expireData.push({
         name: 'Other',
         num: '1'
    })
 console.log(this.expireData)
 //[{name:'001',num:'1'},{name:'orther',num:'1'}]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

打印结果

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/481398
推荐阅读
相关标签
  

闽ICP备14008679号