Home >Common Problem >js string to array

js string to array

百草
百草Original
2023-08-03 13:34:035095browse

JS string to array method: 1. Use the "split()" method to split the string into array elements according to the specified delimiter; 2. Use the "Array.from()" method, Iterable objects or array-like objects can be converted into real arrays; 3. Use a for loop to traverse and add each character to the array in turn; 4. Use the "Array.split()" method by calling "Array.prototype .forEach()" shortcut to split a string into an array.

js string to array

There are many ways to convert strings into arrays in JavaScript. Here are some commonly used methods.

1. Use the split() method

The split() method can split a string into array elements based on the specified delimiter.

var str = "hello world";
var arr = str.split(" "); // 将字符串按空格分割成数组元素
console.log(arr); // ["hello", "world"]

2. Use the Array.from() method

The Array.from() method can convert an iterable object or array-like object into a real array. A string can be converted to an array by passing it as an argument to Array.from().

var str = "hello";
var arr = Array.from(str);  // 将字符串转换为数组
console.log(arr); // ["h", "e", "l", "l", "o"]

3. Use a for loop to traverse the string

You can use a for loop to traverse the string and add each character to the array in turn.

var str = "world";
var arr = [];
for (var i = 0; i < str.length; i++) {
  arr.push(str[i]);
}
console.log(arr); // ["w", "o", "r", "l", "d"]

4. Use the Array.split() method

The Array.split() method is a shortcut to split a string into an array by calling the Array.prototype.forEach() method .

var str = "hello";
var arr = [];
Array.prototype.forEach.call(str, function(char) {
  arr.push(char);
});
console.log(arr); // ["h", "e", "l", "l", "o"]

Summary:

The above are several common methods for converting strings into arrays in JavaScript, including using the split() method, Array.from() method, and for loop to traverse the string and the Array.split() method. You can choose the appropriate method to convert between strings and arrays according to your needs.

The above is the detailed content of js string to array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn