问题描述:

var fruits = ["Apple", "Banana","Pineapple"];

console.log(fruits[0])

console.log(fruits[1])

console.log(fruits[2])

So I've created an array here which contains the name of 3 fruits.

I'm able to log each element in the array using its index number in a separate line but I'm wondering if there's a way I can do this in just 1 line.

Thank you

EDIT: Sorry I didn't make it clear because my example logged all elements. But I want it so that I simply choose which wants I want to log.

So I have an array with the 3 fruits but in one line I just want to log the first and last entry.

网友答案:

join() is what you're looking for. The default separator is a comma so console.log(fruits.join()) will give you

Apple,Banana,Pineapple

The join() method takes a string, so console.log(fruits.join('|')) will give you

Apple|Banana|Pineapple

while console.log(fruits.join(' and ')) will give you

Apple and Banana and Pineapple

The Mozilla Developer Network JavaScript reference is an excellent resource, though of course you first need to know what to look up. Here's the MDN entry for Array.prototype.join()

EDIT: You changed the question while I was answering. To log specific items,

console.log([fruits[0],fruits[2]].join(' and '))

yields

Apple and Pineapple

If you don't mind adding a library to the mix you'll find some excellent helper functions in lodash. The function _.at() might be useful for what you're trying to do (note that join() is unnecessary if you're fine with ', ' as the separator):

console.log(_.at(fruits, [0, 2]))

gives you

Apple, Pineapple

You don't need to put the indices in an array, so console.log(_.at(fruits, 1, 2)) yields

Banana, Pineapple

网友答案:

The following will call console.log for each fruit, so you will see one fruit per line:

fruits.forEach(function(fruit){ console.log(fruit) });

The following will call console.log only once with the fruits as the arguments, so you will see all fruits in the same line:

console.log.apply(console, fruits);
网友答案:

So you mean you want to log "Apple Pineapple"? If so then this will do the trick:

console.log(fruits[0]+" "+fruits[fruits.length-1])
相关阅读:
Top