Skip to content
Advertisement

print array in method in vue.js

I am very new to vue and I wanted to play around with methods a little. What I wanted to try was printing out an array of Strings and this is the method I tried to use:

printStringArray(objectWithArray) {
      i = 0;
      s = '';

      while(i < objectWithArray.stringArray.length) {
        s = objectWithArray.stringArray[i] + s,
      }; 
      return  s;
    },

But I get errors because of i and s. I tried a few things but it always either says I didn’t define or them or I defined them but didn’t use them. Any ideas? I looked at some posts that used working code but if I used that code to see my mistake in comparisons, I get the same erros. I feel like it’s very simple but I can’t find anything on it.

Advertisement

Answer

You can use the following method:

let array = [1, 2, 3, 4];
function printArrayElements(array){
    array.forEach(element => console.log(element))
}

printArrayElements(array);

You can achieve that using the while loop as well:

let array = [1, 2, 3, 4]
function printArrayElement(array){
    let index = 0;
    while (index < array.length){
        console.log(array[index]);
        index +=1;
    }
}

printArrayElement(array);
Advertisement