簡體   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