繁体   English   中英

Javascript 对象 - 检查并循环遍历对象中的数组

[英]Javascript Objects - Check for and loop through arrays in object

我试图遍历一个对象文字,如果一个属性是一个数组,我也想遍历它。 这个对象的朋友属性是一个数组,我将如何测试它是否可迭代,然后循环遍历它?

提前致谢,

  firstName: 'Jonas',
  lastName: 'Schmedtmann',
  age: 2037 - 1991,
  job: 'teacher',
  friends: ['Michael', 'Peter', 'Steven'],
};
const myObj = Object.entries(jonas);
for (const [key, val] of myObj) {
   //Some conditional statement here testing for an interable
   //Then loop through it to the console.
  console.log(key, val);
}

所有数组都是 Javascript 中Array类的实例,因此您可以使用var instanceof Array返回一个布尔值来检查元素是否为数组,然后根据需要对其进行迭代

 const obj = { firstName: 'Jonas', lastName: 'Schmedtmann', age: 2037 - 1991, job: 'teacher', friends: ['Michael', 'Peter', 'Steven'], }; const myObj = Object.entries(obj); for (const [key, val] of myObj) { //Some conditional statement here testing for an interable //Then loop through it to the console. if (val instanceof Array) { console.log('element is an array, printing now') print(val); } else console.log(key, val); } function print(ar) { ar.forEach(x => console.log(x)); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM