How to make JavaScript array from the line
We will show how to use the SPLIT () method to convert a line into an array of JavaScript: "Word1, word2, word3". -> ["Word1", "Word2", "Word3"]
An array is a special type of variable in JavaScript that stores multiple values in a single variable. Arrays are created using the 'array' keyword and assigning the values between square brackets. For example:
var myArray = ["Apple", "Banana", "Orange"];
The above example creates an array called 'myArray' which stores three strings: "Apple", "Banana", and "Orange". To access a value from the array, you can use the array index. The first value of the array is at index 0, the second is at index 1, and so on. For example:
var firstValue = myArray[0]; // firstValue = "Apple"
You can also add additional values to the array using the 'push' method. For example:
myArray.push("Kiwi"); // myArray = ["Apple", "Banana", "Orange", "Kiwi"]
Looping Through an Array
You can loop through the values in an array using a 'for' loop. For example:
for (var i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
// Output:
// Apple
// Banana
// Orange
// Kiwi
The above example loops through the array, printing each value to the console. You can also use the 'forEach' method to loop through an array. For example:
myArray.forEach(function(value) {
console.log(value);
});
// Output:
// Apple
// Banana
// Orange
// Kiwi
The 'forEach' method calls a function for each value in the array, passing the value as an argument to the function. This is useful for performing an action on each value in the array, such as printing the value to the console.