for in for of for each 区别
时间: 2023-10-20 17:30:19 浏览: 91
for循环和for...in循环是用于遍历对象的属性和数组的索引,而for...of循环是用于遍历可迭代对象的元素。
for循环是最常见的循环结构,它可以按照指定的条件重复执行一段代码。在for循环中,我们需要指定一个初始值、一个终止条件和一个每次迭代后执行的操作。
for...in循环用于遍历一个对象的可枚举属性,它会将对象的每个属性名称赋值给指定的变量,并执行相应的操作。通常用于遍历对象而不是数组。
for...of循环用于遍历可迭代对象(如数组、字符串、Set、Map、Generator等)中的元素。它会将对象的每个元素赋值给指定的变量,并执行相应的操作。
for each循环在JavaScript中已经被废弃,不再使用。
相关问题
A trictionary is a pair of tree k and v. They have identical structure: each node in k has a corresponding node in v. The labels in k are called keys. Each key may be the label for multiple nodes in k, and the values for that key are the labels of all the corresponding nodes in v. A lookup function returns one of the values for a key. Specifically, a lookup function for a node in k is a function that takes v as an argument and returns the label for the corresponding node in v. Implement the generator function lookups, which takes as input a tree k and a key. It yields all lookup functions for nodes in k that have key as their label, the functions could be yielded in any order.
Sure, here's a Python implementation of the `lookups` generator function:
```
def lookups(k, key):
"""
Generate all lookup functions for nodes in tree k with label key.
"""
def lookup_fn(node):
"""
Return the label of the corresponding node in v for a given node in k.
"""
return node.value
for node in k.traverse():
if node.label == key:
yield lookup_fn
```
Explanation:
- The `lookups` function takes two arguments: `k`, the tree, and `key`, the label we want to look up.
- The inner function `lookup_fn` takes a node in `v` as an argument and returns its label.
- The function `lookups` uses a `for` loop to traverse all nodes in `k`.
- For each node, it checks whether its label is equal to `key`.
- If the label matches, it yields the `lookup_fn` function for that node.
Note that the implementation assumes that the `Tree` class has a `traverse` method that returns all nodes in the tree in some order, and that each node has a `label` and a `value` attribute. You may need to modify the implementation to match the specifics of your `Tree` class.
for each和for
in Javascript有什么区别?
for each是JavaScript的一个老特性,它可以遍历一个数组、类数组或者对象的可枚举属性,但是现在已经被废弃了,不再是JavaScript的标准语法。
for in则可以遍历一个对象的所有属性名(包括可枚举和不可枚举属性),但是由于它是遍历对象属性名的语法,对于数组的遍历并不适用,适用的是对象的遍历。所以如果要遍历数组的话,推荐使用for of循环。
阅读全文