Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

javascript - How to add comma between array items?

How can I add a comma between the values, when using map function to print out all the values? (Using React, that's why I have the key etc.)

{ cars.map(car => {
    return(
      <p key={car.id}>{car.title} ,</p>
    );
}); }

This is how I would like the result to be, with no comma in the end of the last array item:

Audi, Nissan, Mazda, Toyota

Should I do it somehow like this?

{ cars.map((car, index) => {
  const separator = ", ";
  if(index === car.length - 1) {
     return(
       <p key={car.id}>{car.title} + separator </p>
     );
  }
}); 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can know which call to map's callback is the last by using the index argument you get passed:

{cars.map((car, index) => {
    return(
        <p key={car.id}>{car.title} {index < cars.length - 1 ? ", " : ""}</p>
    );
})}

But note that p is usually a block element, so the cars would be stacked rather than shown inline with spaces (and commas) between them. I'd use span instead (although you can mark the p as inline if you want). I've used span below.

You can also use a concise arrow function rather than a verbose one with a function body:

{cars.map((car, index) =>
    <span key={car.id}>{car.title} {index < cars.length - 1 ? ", " : ""}</span>
)}

Live example:

const cars = [
    {id: 1, title: "Ford"},
    {id: 2, title: "Toyota"},
    {id: 3, title: "Lexus"},
];

ReactDOM.render(
    <div>{cars.map((car, index) =>
        <span key={car.id}>{car.title}{index < cars.length - 1 ? ", " : ""}</span>)
    }</div>,
    document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...