gpt4 book ai didi

javascript - 交换字符串中单词的最佳方法是什么

转载 作者:行者123 更新时间:2023-11-28 17:32:10 26 4
gpt4 key购买 nike

给定以下字符串,我将如何交换左右单词。

即改变

  • “左”->“右”
  • “右”->“左”

let str = JSON.stringify({
val: 4,
right: {
val: 7,
right: { val: 9, right: null, left: null },
left: { val: 6, right: null, left: null },
},
left: {
val: 2,
right: { val: 3, right: null, left: null },
left: { val: 1, right: null, left: null },
},
}, null, 2);

str = str.replace((/"left"/g), o => { return "right1" });
str = str.replace((/"right"/g), o => { return "left1" });

console.log();
console.log(str);

str = str.replace((/"right1"/g), o => { return "right" });

console.log();
console.log(str);

str = str.replace((/"left1"/g), o => { return "left" });

我正在考虑使用 str.replace()。

最佳答案

不要使用字符串操作,保留/解析为对象并交换属性:

function swapLeftRight(obj){
//use object deconstruction to create left and right variables,
//and assign them to the opposite name
let {left:right, right:left} = obj;
//Assign the new values
obj.left = left, obj.right = right;
//Use recursion if the properties are not null
if(obj.left) swapLeftRight(obj.left);
if(obj.right) swapLeftRight(obj.right);
}
var data = {
val: 4,
right: {
val: 7,
right: { val: 9, right: null, left: null },
left: { val: 6, right: null, left: null },
},
left: {
val: 2,
right: { val: 3, right: null, left: null },
left: { val: 1, right: null, left: null },
}
};
swapLeftRight(data);
console.log(data);

关于javascript - 交换字符串中单词的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50068083/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com