javascript - 如何将数组中相邻的数字组合成单个数字并返回一个包含“5”、“6”、“7”、“8”、“9”、“10”、“11”的数组?
问题描述
[“5”、“”、“6”、“”、“7”、“”、“8”、“”、“9”、“”、“1”、“0”、“”、“1” , "1"] 如何更改此数组,以便将同时为“1”、“0”等数字的相邻元素转换为“10”等单个数字?我希望最终的数组有 ["5", "6", "7", "8", "9", "10", "11"]
解决方案
split/replace/join 的评论有点言过其实,但这就是它的工作原理。给定arr = ["5", "", "6", "", "7", "", "8", "", "9", "", "1", "0", "", "1", "1"]
.join(' ') // now we have a string "5 6 7 8 9 1 0 1 1"
5、6、7... 之间有两个空格,而 1 0 和 1 1 之间只有一个空格。
.replace(/\s(\S)/g,"$1")
这用非空格匹配替换空格\s
后跟非空格,\S
即" 0"
"0"
.split(' ')
使用剩余的单个空格将其转换回数组。
一个使用 Array.prototype.reduce 的真实示例:
const numbers = ["5", "", "6", "", "7", "", "8", "", "9", "", "1", "0", "", "1", "1"].reduce( (acc, cur) => {
if( cur === ""){ // if current item is an empty string, create a new placeholder
return [...acc, ""]
}
else { // otherwise append the current number to last entry
acc[acc.length-1] += cur;
return acc;
}
}, [""]) // initialize with an empty string
在第一次迭代acc
中[""]
,我们点击了 a5
所以我们将它添加到 , 的最后一个元素acc
,"" += 5
现在我们有了acc === ["5"]
。下一次迭代命中 a ""
, now acc === ["6", ""]
etc 当它在["5", "6", "7", "8", "9", "1"]
我们命中一个非空字符串时,我们将它添加到现有的"1"
, ie"1" += "0" = "10"
中。
推荐阅读
- php - 正则表达式转换版本错误
- mysql - MySQL - 选择查询错误 1052 上的内部联接
- security - 在 python3 中使用套接字对 TCP 包进行分段并使其重叠?
- jwt - 将 google id_token 交换为一组 keycloak 令牌时出现 invalid_token 错误
- php - 为 foreach() laravel 关系提供的参数无效
- php - PHP我需要在表格中总结奇数和偶数
- python-3.6 - 根据tradingview计算RSI指标?
- python - 站点包中没有 django 文件
- excel - 在 Excel 中加入(匹配)多个列
- javascript - 为什么在 React Hooks 中排序后数组不更新?