SHARE
TWEET

Untitled

a guest Jul 17th, 2017 41 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Prompt: write a function that prints every element inside an array containing nested arrays
  2. var inputArray = [ 1, [2, [3, 4]]];
  3.  
  4. function printElements(array) {
  5.   //loop through the outer array
  6.   for (var i = 0; i < array.length; i++) {
  7.     //if the current element is not an array
  8.     if (!Array.isArray(array[i])) {
  9.       //print it
  10.       console.log(array[i]);
  11.     } else {
  12.         //otherwise, call printElements() again passing in the inner array.
  13.         printElements(array[i]);
  14.       }
  15.   }
  16. }
  17. printElements(inputArray); //logs: 1 2 3 4
RAW Paste Data
Top