在Vue.js官方文档中,v-for directive的所有示例都具有以下格式:
v-for="thing in collection"
其中collection
包含数组和对象。此外,文档指出:
您也可以使用
of
而不是in
作为分隔符,以使其更接近JavaScript的迭代器语法。
This answer解释了普通JavaScript中for..in
和for..of
循环之间的区别。据我了解,for..in
用于循环访问对象的属性,for..of
用于循环访问可迭代的元素。
我的问题是,of
和in
在Vue中的含义与在普通JavaScript中的含义相同吗?
答案 0 :(得分:1)
他们没有
在 Vue.js 中,for..of
和 for..in
是等效的并且可以互换。在 Vue.js 中迭代非常灵活,可以处理各种各样的对象和类型(甚至是整数!注意,TC39!)。
https://v3.vuejs.org/guide/list.html
以下是有效的 Vue.js 代码:
<p v-for="x of {a: 1, b: 2, c: 3}">{{x}}</p>
<p v-for="x in {a: 1, b: 2, c: 3}">{{x}}</p>
<p v-for="x of [1, 2, 3]">{{x}}</p>
<p v-for="x in [1, 2, 3]">{{x}}</p>
所有这些都会打印出1
、2
、3
。
然而,在普通 JavaScript 中,for..of
和 for..in
之间存在差异。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
重要的区别在于,for..of
将迭代可迭代对象,其中 for..in
将迭代可枚举属性。
for (const x of {a: 1, b: 2, c: 3}) {console.log(x);} // TypeError ... is not iterable
for (const x in {a: 1, b: 2, c: 3}) {console.log(x);} // Prints a b c
for (const x of [1, 2, 3]) {console.log(x);} // Prints 1 2 3
for (const x in [1, 2, 3]) {console.log(x);} // Prints 0 1 2 (the indexes)
如您所见,它们的行为非常不同。
即使看起来相同的代码 (for..in {a: 1, b: 2, c: 3}
) 在 Vue.js 和普通 JavaScript 中也会产生不同的结果,一个会打印 1
, 2
, 3
、另一个 a
、b
、c
。