javascript - 将二维单词数组转换为单个数组
问题描述
我有一个数组数组,每个元素中都有句子。我想最终得到一个数组,每个单词都用空格分隔,然后得到整个数组的长度
我知道我需要遍历数组然后应用 split 但是有更好的方法吗?
const temp2 = [
['this is an array'],
['this is a scentence'],
['I love stackoverflow']
]
console.log(
temp2[0][0].split(' ').length // 3 words
)
解决方案
- 使用Array.prototype.flat 将嵌套数组展平为单个数组或单词
- 使用Array.prototype.join将 Array 转换为由空格连接的字符串。
- 用一个或多个空格分割字符串
const temp2 = [
['this is an array'],
['this is a scentence'],
['i love stackoverfloe']
]
const arr = temp2.flat().join(" ").split(/ +/);
console.log(arr); // or use: arr.length
推荐阅读
- php - 如何在 $result->fetch_assoc() 中包含数组?
- php - Ajax 表单向 php 发送空数据
- python - 如何将枕头 EPS 调整为 JPG 质量
- javascript - 更改后如何在javascript中获取完整标签的值?
- php - mysqli_prepare 被跳过
- project-reactor - 记录通量直到单声道完成
- c# - 如何在无模式 WPF 应用程序窗口中立即将子数据发送给父级
- android - 在Android中进行身份验证时出现Instagram重定向问题
- terminal - 如何在不...跳过的情况下在较少的终端中到达文件末尾
- reactjs - 如何从下拉菜单中显示选定的元素