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!

Derick Kolln
  • 633
  • 7
  • 17

6 Answers6

3

Try

path.forEach((each, i)=>{
   console.log ("item" + i+ ':' + each.name );
})
Amoolya S Kumar
  • 1,458
  • 9
  • 10
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);
rfornal
  • 5,072
  • 5
  • 30
  • 42
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])
}
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
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"));
Daerik
  • 4,167
  • 2
  • 20
  • 33
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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

you could use a for loop here , ie,

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