To create a string array in Javascript, you can use the Array object and string literal methods.
Using the from() method of Array objects, you can convert array-like objects or iterable objects into arrays. We can create a string array by converting the string into a character array.
For example, we want to create a string array, which contains the 3 strings "hello", "world" and "Javascript":
let str = "hello world Javascript"; let arr = Array.from(str.split(" ")); console.log(arr); // ["hello", "world", "Javascript"]
We can directly use string literals to create string arrays. In Javascript, we can use square brackets [] to declare an array and separate each string with commas.
For example, we want to create a string array containing the 3 strings "apple", "orange" and "banana":
let fruits = ["apple", "orange", "banana"]; console.log(fruits); // ["apple", "orange", "banana"]
We can also use template literals in the array to create a string array. Template literals are strings used within backticks
where we can insert variables and expressions into the string.
For example, we want to create a string array containing 3 strings "My name is John.", "I am 25 years old." and "I live in New York.":
let name = "John"; let age = 25; let city = "New York"; let info = [`My name is ${name}.`, `I am ${age} years old.`, `I live in ${city}.`]; console.log(info); // ["My name is John.", "I am 25 years old.", "I live in New York."]
Whether we create a string array using an Array object or a string literal, we can use indexing to access and modify each string in the array. For example, if you want to change the first string "hello" to "hi", you can use the following code:
arr[0] = "hi"; console.log(arr); // ["hi", "world", "Javascript"]
Summary:
Array objects and string literals can be used in Javascript Method to create an array of strings. Through these two methods, we can conveniently operate and manage string arrays in code. Choose different methods to create string arrays according to actual needs.
The above is the detailed content of How to create a string array in javascript string. For more information, please follow other related articles on the PHP Chinese website!