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 的语法设计很好地融合了两种遍历方式的特点,让开发者可以根据需要选择合适的写法。

相关推荐
Hyyy15 分钟前
很多Desktop都在上的Computer Use是什么
前端·llm
慢功夫16 分钟前
开篇:VS Code 为什么不是一个普通 React App
前端·visual studio code
你挚爱的强哥27 分钟前
Vue2 实现 1.5s 十连击监听(连续点击若干次),封装通用可复用点击检测工具,不用 data!Vue 封装通用连击监听方法,支持自定义时长与点击次数
前端·javascript·vue.js
huashengzsj1 小时前
Shopify个人建站如何搭建独立站:从零开始的完整指南
前端·网络·人工智能
程序猿小泓1 小时前
从 Claude Code 学 Agent Harness:一个前端工程师的 AI Agent 学习笔记
前端·人工智能·学习
柒和远方2 小时前
从审计日志到可下载证据包:事务型 Outbox、租约 fencing 与保留水位
前端·后端·架构
卓怡学长2 小时前
w266基于spring boot + vue 圣地延安美食乐享系统
java·数据库·vue.js·spring boot·spring·intellij-idea
minglie12 小时前
npm ali-oss库依赖冲突
前端·npm
CryptoPP3 小时前
BSE股票K线数据接入实战:从接口调用到前端图表展示
大数据·前端·网络·人工智能·websocket·网络协议
Random_index4 小时前
#Vue3篇: Vue 项目发版后如何提示用户刷新?基于 package.json 版本号的前端更新检测方案
前端·vue.js·json