Javascript 数据结构和算法

object

  • One answer is to go back to the “classic” way of iterating object properties in JavaScript, before Object.entries() existed, like so:
    const obj = {
      a: 1,
      b: 2,
      c: 3,
    }
    for (const key of Object.keys(obj)) {
      const value = obj[k]
      // Do something with 'value'...
    }
    
  • for of
    for (let group in data) {
       let groupFields = data[group]
    
       groupFields.forEach(field => {
    
       })
    }
    

参考资料

  1. Object.entries()

    The Object.entries() method returns an array of a given object’s own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for…in loop. (The only important difference is that a for…in loop enumerates properties in the prototype chain as well).

  2. TypeScript 3.x: Access properties of type unknown
  3. Object is of type ‘unknown’ - forEach and map

array

Iterating

  • The following example shows how to use the for…of to iterate over elements of an array.
    let scores = [80, 90, 70];
    
    for (let score of scores) {
       score = score + 5;
       console.log(score);
    }
    
  • To access the index of the array elements inside the loop, you can use the for…lop statement with the entries() method of the array.
    The array.entries() method returns a pair of [index, element] in each iteration. For example:
    let colors = ['Red', 'Green', 'Blue'];
    
    for (const [index, color] of colors.entries()) {
       console.log(`${color} is at index ${index}`);
    }
    

参考资料

  1. Introduction to JavaScript for…of Loop in ES6
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值