最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pick first three elements of an array and construct a comma seperated String - Stack Overflow

programmeradmin2浏览0评论

I have an array of fruits. I want to construct a ma separated string of this array for first three elements only. Right now, I am constructing a ma separated string for all.

var fruits = [];

fruits.push("Banana");
fruits.push("Orange");
fruits.push("Apple");
fruits.push("Mango");
fruits.push("Orange");
fruits.push("Papya");
fruits.push("CALAPPLE");

var result = fruits.toString();

alert(result);

Could you please let me know how to achieve this? This is my jsfiddle.

I have an array of fruits. I want to construct a ma separated string of this array for first three elements only. Right now, I am constructing a ma separated string for all.

var fruits = [];

fruits.push("Banana");
fruits.push("Orange");
fruits.push("Apple");
fruits.push("Mango");
fruits.push("Orange");
fruits.push("Papya");
fruits.push("CALAPPLE");

var result = fruits.toString();

alert(result);

Could you please let me know how to achieve this? This is my jsfiddle.

Share Improve this question edited Jun 7, 2015 at 15:18 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked Jun 7, 2015 at 14:42 PawanPawan 32.4k109 gold badges268 silver badges447 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 8

Slice the array with Array.prototype.slice, which will return a new array with only the sliced elements and join them with Array.prototype.join, like this

console.log(fruits.slice(0, 3).join(", "));
// Banana, Orange, Apple

Here, we say that start slicing from index zero, till three. The last element will not be included in the slice. So, from the index zero, we get the elements at index zero, one and two.


If you don't want to create a new array with slice, you can just use a simple for loop and do it like this

var result = "";
for (var i = 0; i < 2; i += 1) {
    result += fruits[i] + ", ";
}
result += fruits[i];

console.log(result);
// Banana, Orange, Apple

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论