For of/for in的区别
时间: 2024-05-14 20:13:55 浏览: 7
"for of"和"for in"都是JavaScript中的迭代器,但它们的用途不同。
"for of"用于迭代可迭代对象的值,例如数组、字符串等。
例如:
```
const arr = [1, 2, 3];
for (const value of arr) {
console.log(value); // 1, 2, 3
}
const str = "hello";
for (const char of str) {
console.log(char); // h, e, l, l, o
}
```
"for in"用于迭代对象的属性名称,例如对象的键。
例如:
```
const obj = {a: 1, b: 2, c: 3};
for (const key in obj) {
console.log(key); // a, b, c
}
```
需要注意的是,"for in"迭代的是对象的属性名称,而不是属性的值。因此,如果需要获取属性的值,需要使用对象的[key]语法。
例如:
```
const obj = {a: 1, b: 2, c: 3};
for (const key in obj) {
console.log(obj[key]); // 1, 2, 3
}
```
相关问题
for in/for of
`for in` and `for of` are both loops used in JavaScript for iteration, but they have different use cases and syntax.
`for in`:
The `for in` loop is used for iterating over the properties of an object. It is generally used with objects, and not with arrays or strings. The syntax of `for in` is:
```
for (variable in object) {
// code to be executed
}
```
Here, `variable` represents a property name of the object, and `object` is the object being iterated. The loop will iterate over all the enumerable properties of the object, including those inherited from its prototype chain.
Example:
```
const person = {
name: 'John',
age: 30,
gender: 'male'
};
for (let property in person) {
console.log(`${property}: ${person[property]}`);
}
// Output:
// name: John
// age: 30
// gender: male
```
`for of`:
The `for of` loop is used for iterating over the values of an iterable object, such as an array or a string. The syntax of `for of` is:
```
for (variable of iterable) {
// code to be executed
}
```
Here, `variable` represents the value of each element in the iterable, and `iterable` is the iterable object being iterated. The loop will iterate over all the elements of the iterable, in the order they appear.
Example:
```
const colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}
// Output:
// red
// green
// blue
```
In summary, `for in` is used for iterating over properties of an object, while `for of` is used for iterating over values of an iterable object.
for of和for in区别
for...in和for...of都是用来遍历的属性,但是它们有以下区别:
共性:
- 都可以遍历数组和对象
区别:
- for...in语句用于遍历对象的属性,而for...of语句用于遍历可迭代对象的元素
- for...in语句返回的是对象的键名,而for...of语句返回的是对象的键值
- for...in语句可以遍历对象的原型链上的属性,而for...of语句不行
- for...in语句可以遍历字符串类型的键名,而for...of语句不行
以下是两个例子来说明它们的区别:
1. 遍历对象
```javascript
const obj = { a: 1, b: 2, c: 3 }
// for...in语句遍历对象的属性
for (let i in obj) {
console.log(i) // 输出:a b c
}
// for...of语句不能用于对象
for (let i of obj) {
console.log(i) // 输出:Uncaught TypeError: obj is not iterable 报错了
}
```
2. 遍历数组
```javascript
const arr = [1, 2, 3]
// for...in语句遍历数组的下标
for (let i in arr) {
console.log(i) // 输出:0 1 2
}
// for...of语句遍历数组的元素
for (let i of arr) {
console.log(i) // 输出:1 2 3
}
```