2

I want to show up the names of the members of an array "path" in my console.

console.log("start: ", path[0].name, "second: ", path[1].name, "third: ", path[2]name, ....)

But the problem is, that my array always changes it's size (clicking algorithm), that means sometimes it has the lenght 4 or sometimes 8 ect. How can i adjust the console.log code to this dynamic array? Thanks so much!

4
  • 1
    check length of array and use for loop Commented Nov 30, 2016 at 17:54
  • thanks so much to all of you....so many different suggestions, i don't know where to start :) Commented Nov 30, 2016 at 18:05
  • 1
    wherever you want but don't start from nina's answer .she is little advanced. Commented Nov 30, 2016 at 18:07
  • nina's version is crazy ;) i am a beginner and i cannot even read her second line Commented Nov 30, 2016 at 18:12

6 Answers 6

3

Try

path.forEach((each, i)=>{
   console.log ("item" + i+ ':' + each.name );
})
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this:

var path = ['Prit', 'Bab', 'Nav']
var item = ["first","second", "third"]; 
for (i = 0; i < path.length;i++){
    console.log(item[i] + ":" + path[i])
}

2 Comments

Ok, now it works on my console. But is there a chance to make them appear on screen like this? 1. element: name1, 2. element: name2, 3. element: name3 .........
@DerickKolln just change console.log to document.write
1

Try something like this for single line result set ...

var result = "";
for (var i = 0, len = path.length; i < len; i++) {
  if (i !== 0) {
    result += ", ";
  }
  result += (i + 1) + ": " + path[i].name;
}
console.log(result);

Comments

1

you could use a for loop here , ie,

for (var i=0;i<path.length;i++) {
   console.log("item no "+ i +": " + path[i]);
}

Comments

1

/* Console Array */
var consoleArray = new Array;

/* Names */
var path = [
    {name: 'bob'},
    {name: 'jimmy'},
    {name: 'chris'},
    {name: 'alexander'},
    {name: 'mark'}
];

/* Loop */
for(var i = 0; i < path.length; i++) {
    consoleArray.push((i + 1) + ': ' + path[i].name);
}

/* Console Log */
console.log(consoleArray.join("\n"));

Comments

1

With ES6, you could use spread syntax ....

var path = [{ name: 'Jo'}, { name: 'John'}, { name: 'Jane'}];
console.log(...path.map((a, i) => (i ? i + 1 : 'Start') + ': ' + a.name));

Comments

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.