如何获取多个字符串的总长度?

Vic*_*obe 0 javascript

我必须获取或计算多个字符串中有多少个字符。例子:

var aText = [
  "There are only 2 types of people in the world:",
  "Girls and boys, any other thing? I don't know."
];
Run Code Online (Sandbox Code Playgroud)

两个字符串加起来超过 80 个字符。另一个注意事项是字符串可能不固定,因为它们可能会增加或减少。有没有办法在 JavaScript 中做到这一点?

我尝试使用aText.length,但这只返回变量中的字符串数量。在本例中只有 2 个。

小智 5

是的你可以。要查找数组内所有字符串中的字符长度,您可以使用array.join('').length

.join('')将数组中的所有字符串连接在一起形成一个字符串,它们之间没有分隔符。之后.length属性用于计算结果字符串中的字符总数。检查这个例子:

const myArray = Array("A", "BB", "CCC")

console.log(myArray.join("").length);
Run Code Online (Sandbox Code Playgroud)