JavaScript 和 Vue3 中 for...in 与 for...of 的区别

我来详细解释一下 JavaScript 和 Vue3 中 for...infor...of 的区别。

参考 列表渲染 | Vue.js

在 JavaScript 中的区别

for...in

  • 用途 :遍历对象的可枚举属性名(键名)
  • 遍历内容:属性名/索引
  • 适用对象:对象、数组、字符串等
javascript 复制代码
// 遍历对象
const obj = { name: 'Alice', age: 25, city: 'Beijing' };
for (let key in obj) {
    console.log(key); // name, age, city
    console.log(obj[key]); // Alice, 25, Beijing
}

// 遍历数组
const arr = ['a', 'b', 'c'];
for (let index in arr) {
    console.log(index); // 0, 1, 2 (注意:是字符串)
    console.log(arr[index]); // a, b, c
}

for...of

  • 用途 :遍历可迭代对象的值
  • 遍历内容:属性值
  • 适用对象:数组、字符串、Map、Set、NodeList 等
javascript 复制代码
// 遍历数组
const arr = ['a', 'b', 'c'];
for (let value of arr) {
    console.log(value); // a, b, c
}

// 遍历字符串
const str = 'hello';
for (let char of str) {
    console.log(char); // h, e, l, l, o
}

// 遍历 Map
const map = new Map([['name', 'Alice'], ['age', 25]]);
for (let [key, value] of map) {
    console.log(key, value); // name Alice, age 25
}

在 Vue3 中的使用

在模板中使用 v-for

vue 复制代码
<template>
  <!-- 使用 for...of 的思想:遍历值 -->
  <ul>
    <li v-for="item in items" :key="item.id">
      {{ item.name }}
    </li>
  </ul>
  
  <!-- 遍历对象属性:类似 for...in -->
  <div v-for="(value, key) in user" :key="key">
    {{ key }}: {{ value }}
  </div>
  
  <!-- 获取索引:类似 for...in 的索引 -->
  <div v-for="(item, index) in items" :key="item.id">
    {{ index }}: {{ item.name }}
  </div>
</template>

<script setup>
import { ref } from 'vue'

const items = ref([
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Orange' }
])

const user = ref({
  name: 'Alice',
  age: 25,
  city: 'Beijing'
})
</script>

在 Composition API 中使用

vue 复制代码
<script setup>
import { ref, onMounted } from 'vue'

const users = ref([
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 35 }
])

const userInfo = ref({
  name: 'Alice',
  age: 25,
  email: 'alice@example.com'
})

onMounted(() => {
  // 使用 for...of 遍历数组值
  for (const user of users.value) {
    console.log(user.name, user.age)
  }
  
  // 使用 for...in 遍历对象属性
  for (const key in userInfo.value) {
    console.log(key, userInfo.value[key])
  }
  
  // 注意:Vue3 的响应式对象可能包含额外属性
  for (const key in userInfo.value) {
    // 过滤掉 Vue 内部属性
    if (userInfo.value.hasOwnProperty(key)) {
      console.log(key, userInfo.value[key])
    }
  }
})
</script>

实际应用对比

javascript 复制代码
// 原始数据
const products = [
  { id: 1, name: 'iPhone', price: 999 },
  { id: 2, name: 'iPad', price: 599 }
]

const productMap = {
  '1': { name: 'iPhone', price: 999 },
  '2': { name: 'iPad', price: 599 }
}

// JavaScript 中的遍历
console.log('=== for...in ===')
for (let index in products) {
    console.log('Index:', index, 'Type:', typeof index) // 字符串类型
    console.log('Value:', products[index])
}

for (let key in productMap) {
    console.log('Key:', key)
    console.log('Value:', productMap[key])
}

console.log('=== for...of ===')
for (let product of products) {
    console.log('Product:', product)
}

// Vue3 模板中的对应写法
vue 复制代码
<template>
  <!-- 对应 for...in 遍历数组索引 -->
  <div v-for="(product, index) in products" :key="index">
    Index: {{ index }} <!-- 这里的 index 类似 for...in 的 key -->
    Product: {{ product.name }}
  </div>
  
  <!-- 对应 for...in 遍历对象 -->
  <div v-for="(value, key) in productMap" :key="key">
    Key: {{ key }} <!-- 对应 for...in 的属性名 -->
    Value: {{ value }} <!-- 对应 for...in 的属性值 -->
  </div>
  
  <!-- 对应 for...of 遍历值 -->
  <div v-for="product in products" :key="product.id">
    {{ product.name }} - ${{ product.price }} <!-- 直接使用值 -->
  </div>
</template>

关键区别总结

特性 for...in for...of
遍历内容 属性名/索引 属性值
数据类型 对象、数组等 可迭代对象
索引类型 字符串 数字
Vue模板 (value, key) value
适用场景 遍历对象属性 遍历数组元素

在 Vue3 中,v-for 的语法设计很好地融合了两种遍历方式的特点,让开发者可以根据需要选择合适的写法。

相关推荐
知识分享小能手1 小时前
微信小程序入门学习教程,从入门到精通,微信小程序常用API(上)——知识点详解 + 案例实战(4)
前端·javascript·学习·微信小程序·小程序·html5·微信开放平台
清灵xmf2 小时前
CSS field-sizing 让表单「活」起来
前端·css·field-sizing
文火冰糖的硅基工坊2 小时前
[光学原理与应用-480]:《国产检测设备对比表》
前端·人工智能·系统架构·制造·半导体·产业链
excel2 小时前
Qiankun 子应用生命周期及使用场景解析
前端
weixin_446260852 小时前
Django - 让开发变得简单高效的Web框架
前端·数据库·django
ObjectX前端实验室3 小时前
【react18原理探究实践】异步可中断 & 时间分片
前端·react.js
SoaringHeart3 小时前
Flutter进阶:自定义一个 json 转 model 工具
前端·flutter·dart
努力打怪升级4 小时前
Rocky Linux 8 远程管理配置指南(宿主机 VNC + KVM 虚拟机 VNC)
前端·chrome
brzhang4 小时前
AI Agent 干不好活,不是它笨,告诉你一个残忍的现实,是你给他的工具太难用了
前端·后端·架构
brzhang4 小时前
一文说明白为什么现在 AI Agent 都把重点放在上下文工程(context engineering)上?
前端·后端·架构