Hello! 欢迎来到小浪资源网!



js怎么遍历对象


要遍历 JavaScript 对象,可以使用以下方法:1. for…in 循环;2. Object.keys() 方法;3. object.values() 方法;4. object.entries() 方法;5. foreach() 方法。

js怎么遍历对象

如何使用 JavaScript 遍历对象

要遍历 JavaScript 对象,可以使用以下方法:

1. for…in 循环

const obj = {   name: "John Doe",   age: 30,   city: "New York" };  for (let key in obj) {   console.log(key); // 输出 "name", "age", "city" }

2. Object.keys() 方法

const obj = {   name: "John Doe",   age: 30,   city: "New York" };  const keys = Object.keys(obj); console.log(keys); // 输出 ["name", "age", "city"]

3. Object.values() 方法

const obj = {   name: "John Doe",   age: 30,   city: "New York" };  const values = Object.values(obj); console.log(values); // 输出 ["John Doe", 30, "New York"]

4. Object.entries() 方法

const obj = {   name: "John Doe",   age: 30,   city: "New York" };  const entries = Object.entries(obj); console.log(entries); // 输出 [["name", "John Doe"], ["age", 30], ["city", "New York"]]

5. foreach() 方法

const obj = {   name: "John Doe",   age: 30,   city: "New York" };  obj.forEach((value, key) => {   console.log(`${key}: ${value}`); });

相关阅读