JavaScript 中将字符串转换为数组
我们需要完成的任务是在 JavaScript 中将输入字符串转换为数组。
无论何时我们尝试将一个字符串单词分解成字符,或者将一个句子分解成单词——拆分成数组,我们都有一些内置方法可以将字符串转换为数组。
在本文中,我们将讨论如何在 JavaScript 中使用不同的方法将字符串转换为数组。
使用 split() 方法
此方法将字符串拆分为子字符串数组。这将在一个新数组中返回输出,并且不会更改现有字符串。
split() 方法 接受 2 个参数,并且这两个参数都是可选参数,第一个是 **分隔符**。它将描述每个拆分应该发生的位置,并且可以是字符串或正则表达式。如果我们没有传递任何参数,它将返回数组中的整个字符串。
第二个参数是 **限制**,输入应为一个整数,它将限制拆分的数量。
示例 1
以下是使用 split() 方法将字符串转换为数组的示例 -
<!DOCTYPE html> <html> <title>Converting string to an array in JavaScript</title> <head> <script> var string = "We are Tutorials point"; const arr1 = string.split(' '); const arr2 = string.split(''); const arr3 = string.split(" ", 2) document.write(arr1, "<br>", arr2, "<br>", arr3, "<br>"); let [first, second, third, fourth] = string.split(' '); document.write(first, second, third, fourth); </script> </head> <body> </body> </html>
示例 2
使用特殊字符的 split 方法
在下面的示例中,输入句子中包含一些特殊字符。并且我们在 split() 方法中传递了这些特殊字符。每当字符串中与这些字符匹配时,它将在那里拆分句子并在输出中删除特殊字符。
<!DOCTYPE html> <html> <title>Converting string to an array in JavaScript</title> <head> <script> var string = "Oh, you are working tutorialspoint? that place is amazing! how can i join there; is there any vacancy? please let me know."; const array = string.split(/[.,!,?,;]/); document.write(array); </script> </head> <body> </body> </html>
使用 Array.from() 方法
我们还可以使用 Array.from() 方法执行上述任务。
Array.from() 方法将从任何具有 length 属性的对象以及任何可迭代对象返回一个数组作为输出。它接受一个参数对象以转换为数组。
示例
以下是示例,我们使用 Array.from() 方法将字符串转换为数组 -
<!DOCTYPE html> <html> <title>Converting string to an array in JavaScript</title> <head> <script> let string = "Tutorix"; let arr = Array.from(string); document.write(arr); </script> </head> <body> </body> </html>
使用扩展运算符(...)
扩展 (...) 运算符 可以将数组或字符串的元素扩展为一系列值。
如果我们在没有扩展运算符的情况下传递字符串,它不会扩展字符串的字符,而是会将整个字符串作为数组中的单个元素打印。
let string = "hello world my name "; let array = [string]; document.write.log(array); // output: ["hello world my name "]
因此,我们可以通过使用扩展 (…) 运算符来避免这种情况。使用此扩展运算符,它将提取字符串的元素作为一系列值。
示例
以下是将字符串转换为数组的示例 -
<!DOCTYPE html> <html> <title>Converting string to an array in JavaScript</title> <head> <script> let string = "Let's go to new york"; let arr = [...string]; document.write(arr); </script> </head> <body> </body> </html>
使用 Object.assign() 方法
Object.assign() 方法将从源对象复制所有属性到目标对象。它接受两个参数,一个是目标,第二个是源,它返回目标对象。
以下是 Object.assign() 方法的语法 -
Object.assign(target, sources)
示例
在下面的示例中,我们声明了源对象并将源作为源参数传递给 object.assign() 以及一个空数组作为目标参数。这将把字符串中的元素返回到数组中。
<!DOCTYPE html> <html> <title>Converting string to an array in JavaScript</title> <head> <script> let string = "Arjun reddy is a cult classic"; let arr = Object.assign([], string); document.write(arr); </script> </head> <body> </body> </html>
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP