-1

I use the bellow code to get my requirement text:

var ipv4s = [
  {ip: '1.1.1.1'},
  {ip: '1.1.1.2'},
  {ip: '1.1.1.3'},
  {ip: '1.1.1.4'},
  {ip: '1.1.1.5'},
  {ip: '1.1.1.6'},
]

var ip_text = ''
for (let index in ipv4s) {

  var item = ipv4s[index]

  if(index === (ipv4s.length -1) ){

    ip_text += item.ip
  }else {
    ip_text += (item.ip + ", ")
  }
  console.log(index, ipv4s.length - 1)
}

console.log(ip_text)

But I get the bellow console:

0 5
1 5
2 5
3 5
4 5
5 5
1.1.1.1, 1.1.1.2, 1.1.1.3, 1.1.1.4, 1.1.1.5, 1.1.1.6, 

But in my think it will get the 1.1.1.1, 1.1.1.2, 1.1.1.3, 1.1.1.4, 1.1.1.5, 1.1.1.6.

why there is a redundant , in there?

lustre
  • 119
  • 1
  • 16
  • 2
    `ipv4s.map( item => item.ip ).join( ', ' );` This is a good example why using for...in on an array is usually not the best way to code something. – Shilly Sep 25 '18 at 12:18
  • @Shilly also, [`for...in` is probably a bad idea anyway](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – VLAZ Sep 25 '18 at 12:27
  • @vlaz That's what I meant with `using for...in on an array is usually not the best way`. Tbh, I've never used a for ... in loop for anything. Collection management is all array methods and destructuring. And state management is usually direct reference. – Shilly Sep 25 '18 at 13:02
  • The only real time I've used `for...in` is when iterating over an *object*. And even then it was before we had nicer ways to do it natively. And even then, I soon replaced it with using Underscore.JS. – VLAZ Sep 25 '18 at 13:05

1 Answers1

4

This is because of the type of index in your function is string. you can use typeof(index) to check it.

So, you can not use === for check equal.

aircraft
  • 25,146
  • 28
  • 91
  • 166