0

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.

2
  • Is there a specific reason you're not using a forEach loop? It's usually easier for iterating through arrays. Commented Feb 8, 2021 at 10:40
  • Because I wanted to use a while-loop before I try forEach-loops. Commented Feb 8, 2021 at 10:50

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Oh, that was good! With let they finally accepted my s as defined AND used. Perfect thanks! I knew it was something super small.. :)
In while loop example change the console.log(array[a]); to console.log(array[index]);
Thanks, I replaced it with the correct argument name @Makesh
1

It's more about javascript than it is vue. To the point:

You have a function called toString that does that for you. Here's a snippet:

const stuff = [0, 1, "Apple", "Mango"];
const x = fruits.toString();
console.log(x);

Comments

1

You've the possibility to use the join method and show the items separated by space :

printStringArray(objectWithArray) {
      let joined=objectWithArray.join(" ");
      console.log(joined)
     return joined;
    },

2 Comments

So many good answers! I love this one! I didn't know I could do that :)
you're welcome, thanks to giving me my first 10 points, you also use any separator in join method like join("/")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.