最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

js使用for...of遍歷對(duì)象

 更新時(shí)間:2026年05月28日 15:51:56   作者:代碼獵人  
本文主要介紹了js使用for...of遍歷對(duì)象,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

雖然普通對(duì)象默認(rèn)不支持 for...of,但有多種方法可以實(shí)現(xiàn):

1.使用 Object 的輔助方法

遍歷鍵名 (keys)

const obj = { a: 1, b: 2, c: 3 };

// 方法1: Object.keys()
for (const key of Object.keys(obj)) {
  console.log(key); // 'a', 'b', 'c'
  console.log(obj[key]); // 1, 2, 3
}

// 方法2: 使用數(shù)組的解構(gòu)和循環(huán)
for (const key of Object.keys(obj)) {
  const value = obj[key];
  console.log(key, value);
}

遍歷值 (values)

const obj = { a: 1, b: 2, c: 3 };

for (const value of Object.values(obj)) {
  console.log(value); // 1, 2, 3
}

遍歷鍵值對(duì) (entries)

const obj = { a: 1, b: 2, c: 3 };

// 方法1: 使用數(shù)組解構(gòu)
for (const [key, value] of Object.entries(obj)) {
  console.log(key, value); // 'a' 1, 'b' 2, 'c' 3
}

// 方法2: 不使用解構(gòu)
for (const entry of Object.entries(obj)) {
  const key = entry[0];
  const value = entry[1];
  console.log(key, value);
}

2.使對(duì)象本身可迭代 (實(shí)現(xiàn) Symbol.iterator)

基本實(shí)現(xiàn)

const obj = {
  name: 'John',
  age: 30,
  city: 'New York',
  
  // 添加 Symbol.iterator 方法
  [Symbol.iterator]: function* () {
    // 遍歷自身屬性
    for (const key of Object.keys(this)) {
      yield [key, this[key]];
    }
  }
};

// 現(xiàn)在可以用 for...of 直接遍歷
for (const [key, value] of obj) {
  console.log(`${key}: ${value}`);
}
// 輸出:
// name: John
// age: 30
// city: New York

只返回值的迭代器

const obj = {
  a: 1,
  b: 2,
  c: 3,
  [Symbol.iterator]: function* () {
    for (const key of Object.keys(this)) {
      yield this[key];
    }
  }
};

for (const value of obj) {
  console.log(value); // 1, 2, 3
}

3.自定義迭代行為

按特定順序迭代

const user = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30,
  email: 'john@example.com',
  
  [Symbol.iterator]: function* () {
    // 自定義迭代順序
    yield ['姓名', `${this.firstName} ${this.lastName}`];
    yield ['年齡', this.age];
    yield ['郵箱', this.email];
  }
};

for (const [label, value] of user) {
  console.log(`${label}: ${value}`);
}
// 輸出:
// 姓名: John Doe
// 年齡: 30
// 郵箱: john@example.com

只迭代特定屬性

const product = {
  id: 1,
  name: 'Laptop',
  price: 999.99,
  category: 'Electronics',
  inStock: true,
  
  [Symbol.iterator]: function* () {
    // 只迭代非布爾值的屬性
    const keys = Object.keys(this);
    for (const key of keys) {
      if (typeof this[key] !== 'boolean') {
        yield [key, this[key]];
      }
    }
  }
};

for (const [key, value] of product) {
  console.log(`${key}: ${value}`);
}
// 輸出:
// id: 1
// name: Laptop
// price: 999.99
// category: Electronics

4.類實(shí)例的可迭代性

class UserCollection {
  constructor() {
    this.users = [];
  }
  
  add(user) {
    this.users.push(user);
  }
  
  // 使實(shí)例可迭代
  *[Symbol.iterator]() {
    for (const user of this.users) {
      yield user;
    }
  }
  
  // 或者返回鍵值對(duì)
  *entries() {
    for (let i = 0; i < this.users.length; i++) {
      yield [i, this.users[i]];
    }
  }
}

const collection = new UserCollection();
collection.add({ name: 'Alice', age: 25 });
collection.add({ name: 'Bob', age: 30 });

// 遍歷用戶
for (const user of collection) {
  console.log(user.name, user.age);
}

// 遍歷帶索引的用戶
for (const [index, user] of collection.entries()) {
  console.log(index, user.name);
}

5.使用生成器函數(shù)

function* objectEntries(obj) {
  for (const key of Object.keys(obj)) {
    yield [key, obj[key]];
  }
}

const obj = { x: 10, y: 20, z: 30 };

for (const [key, value] of objectEntries(obj)) {
  console.log(key, value);
}

6.實(shí)際應(yīng)用場(chǎng)景

場(chǎng)景1:遍歷配置對(duì)象

const config = {
  apiUrl: 'https://api.example.com',
  timeout: 5000,
  retries: 3,
  debug: false
};

// 配置迭代器
config[Symbol.iterator] = function* () {
  const keys = Object.keys(this).sort(); // 按字母排序
  for (const key of keys) {
    yield { key, value: this[key] };
  }
};

for (const { key, value } of config) {
  if (typeof value !== 'boolean') { // 過濾布爾值
    console.log(`配置 ${key} = ${value}`);
  }
}

場(chǎng)景2:處理嵌套對(duì)象

const company = {
  name: 'TechCorp',
  departments: {
    engineering: { employees: 50, budget: 1000000 },
    sales: { employees: 20, budget: 500000 },
    marketing: { employees: 15, budget: 300000 }
  }
};

// 扁平化迭代器
company[Symbol.iterator] = function* () {
  yield ['公司名稱', this.name];
  for (const [dept, info] of Object.entries(this.departments)) {
    yield [`${dept}部門人數(shù)`, info.employees];
    yield [`${dept}部門預(yù)算`, info.budget];
  }
};

for (const [label, value] of company) {
  console.log(`${label}: ${value}`);
}

7.性能考慮

const obj = {};
// 創(chuàng)建一個(gè)大對(duì)象
for (let i = 0; i < 1000000; i++) {
  obj[`key${i}`] = i;
}

// 測(cè)試不同方法的性能
console.time('Object.keys + for...of');
for (const key of Object.keys(obj)) {
  const value = obj[key];
}
console.timeEnd('Object.keys + for...of');

console.time('Object.entries + for...of');
for (const [key, value] of Object.entries(obj)) {
  // 直接有值
}
console.timeEnd('Object.entries + for...of');

console.time('for...in');
for (const key in obj) {
  if (obj.hasOwnProperty(key)) {
    const value = obj[key];
  }
}
console.timeEnd('for...in');

8.實(shí)用工具函數(shù)

// 創(chuàng)建可迭代對(duì)象的工具函數(shù)
function makeIterable(obj, options = {}) {
  const {
    exclude = [],      // 排除的屬性
    includeOnly = null, // 只包含的屬性
    sortKeys = false,  // 是否按鍵排序
    valueOnly = false  // 只返回值
  } = options;
  
  const iterable = { ...obj };
  
  iterable[Symbol.iterator] = function* () {
    let keys = Object.keys(this);
    
    // 過濾
    if (exclude.length) {
      keys = keys.filter(key => !exclude.includes(key));
    }
    
    if (includeOnly) {
      keys = keys.filter(key => includeOnly.includes(key));
    }
    
    // 排序
    if (sortKeys) {
      keys.sort();
    }
    
    // 迭代
    for (const key of keys) {
      if (valueOnly) {
        yield this[key];
      } else {
        yield [key, this[key]];
      }
    }
  };
  
  return iterable;
}

// 使用示例
const data = { a: 1, b: 2, c: 3, d: 4, e: 5 };
const iterableData = makeIterable(data, {
  exclude: ['e'],
  sortKeys: true
});

for (const [key, value] of iterableData) {
  console.log(key, value); // a 1, b 2, c 3, d 4
}

總結(jié)

  1. 最簡(jiǎn)單的方法:使用 Object.keys()、Object.values() 或 Object.entries()
  2. 需要直接迭代對(duì)象:實(shí)現(xiàn) Symbol.iterator 方法
  3. 需要自定義迭代邏輯:使用生成器函數(shù)
  4. 考慮性能Object.entries() + for...of 通常是性能和可讀性的最佳平衡
// 推薦的最佳實(shí)踐
const obj = { a: 1, b: 2, c: 3 };

// 1. 只需要鍵或值
for (const key of Object.keys(obj)) { }
for (const value of Object.values(obj)) { }

// 2. 需要鍵值對(duì)
for (const [key, value] of Object.entries(obj)) { }

// 3. 需要直接迭代對(duì)象(添加迭代器)
obj[Symbol.iterator] = function* () {
  for (const [key, value] of Object.entries(this)) {
    yield { key, value };
  }
};

到此這篇關(guān)于js使用for...of遍歷對(duì)象的文章就介紹到這了,更多相關(guān)js for of遍歷對(duì)象內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

岳阳市| 治多县| 鱼台县| 马龙县| 咸宁市| 库车县| 崇明县| 封开县| 永新县| 灵璧县| 漠河县| 都匀市| 大英县| 西城区| 石门县| 孟州市| 义乌市| 温泉县| 鹤壁市| 大荔县| 南漳县| 包头市| 正阳县| 白银市| 临海市| 锡林郭勒盟| 沁水县| 阜康市| 延边| 新乡县| 揭阳市| 沙湾县| 周至县| 通化市| 武功县| 久治县| 马山县| 普安县| 香格里拉县| 佳木斯市| 富宁县|