Corsi registrati su
Corsi in diretta per la formazione di Front End Developer e Back End Developer
This method is similar to the previous toString, discussed in the previous lesson. The difference with the toString method is that the latter can also be used on other variables, while join is used only with arrays.
Also in this case the original array remains unchanged, so we have to store the result in another variable, and then use it where appropriate.
Let’s now deal with practical examples to understand how it works.
As a first example let’s convert a simple array of numbers into a string, using the join () method.
So let’s assume we have the following array of numbers:
var numbers = [5,4,3,2,6,9,62];
We then use the join method to convert the array and store the result in a variable, such as a string name.
Then we display the result in the browser console.
var str = numbers.join(); console.log(str);
In this way we will get numbers separated by a comma.
We propose the same example again but with an array of strings, so we repeat the example above by changing only the array.
For example, if by hypothesis we have the following array:
var objectsSchools = ['pencil', 'eraser', 'sharpener', 'notebook', 'pencil'];
And then we apply the join method to the array of starting strings, displaying the result for simplicity always in the browser console.
var str = objectsSchools.join('-'); console.log(str);
We will display the following result: pencil – eraser – sharpener – notebook – pencil.