如何用正则替换JS字符串变量部分,实现特定对象旋转值转换
问题说明
给定如下JS对象:
{"name":"a","rotation":2}
需要将所有name为a、b、c或i的对象,若其rotation当前为2则转为0,若为3则转为1。
上述示例的预期输出为:
{"name":"a","rotation":0}
实际场景中,这些对象被用于一个4×5规模的二维数组,示例如下:
[ [{"name":"a","rotation":2}, {"name":"e","rotation":0}], [{"name":"c","rotation":2}, {"name":"j","rotation":2}] ]
为避免遍历二维数组,考虑使用正则表达式方案。这些对象代表棋盘状态,目标是判断当前棋盘状态是否与解一致——将棋盘转为JSON字符串后用===与解对比。
问题在于,对称棋子的rotation0 === rotation2且rotation1 === rotation3,因此需要将name为a、b、c、i的对象的rotation值2替换为0,3替换为1。
我的尝试
尝试过非捕获组(?:)等方法,但未成功。以下代码展示了问题:在replace的第二个参数中无法用[abci]获取原字符,因为需要替换整个匹配内容。
let obj = '{"name":"b","rotation":2}'; obj.replace( /"name":"[abci]","rotation":2/g, '"name":"[abci]","rotation":0' ); // Expected: {"name":"b","rotation":0}
解决方案
正则表达式方案(耗时约380ms)
let symetricBoard = JSON.stringify(this.board) .replace(/"name":"([abci])","rotation":2/g, '"name":"$1","rotation":0') .replace(/"name":"([abci])","rotation":3/g, '"name":"$1","rotation":1');
二维数组遍历方案(耗时约14ms)
let symetricBoard = this.board; for (let col = 0; col < this.cols; col++) { for (let row = 0; row < this.rows; row++) { let tile = board[col][row]; if (tile && "abci".includes(tile.name) && tile.rotation > 1) { board[col][row].rotation = (tile.rotation - 2 + 4) % 4; } } }
内容的提问来源于stack exchange,提问作者Bledder
相关产品推荐
相关产品推荐

