在 JavaScript 中将字符串转换为数组

javascriptweb developmentfront end technology

我们需要完成的任务是在 JavaScript 中将输入字符串转换为数组。

每当我们尝试将字符串单词分解为字符或将句子分解为单词(分解为数组)时,我们都有内置方法将字符串转换为数组。

在本文中,我们将讨论如何使用 JavaScript 中的不同方法将字符串转换为数组。

使用 split() 方法

此方法将字符串拆分为子字符串数组。这将在新数组中返回输出,并且不会更改现有字符串。

split() 方法接受 2 个参数,并且都是可选参数,第一个是分隔符。它将描述每次拆分应发生的位置,可以是字符串或正则表达式。如果我们没有传递任何参数,它将返回数组中的整个字符串。

第二个参数是limit,输入应该是一个整数,它将限制拆分的数量。

示例 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() 方法中。只要字符串中存在与这些字符匹配的字符,它就会在那里拆分句子并删除输出中的特殊字符。

<!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); // 输出:["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>


相关文章