如何增量替换 classList 中的标记?
我想找到一种方法,使用更少的代码行将标记“c1”替换为“c2”,将“c2”替换为“c3”等。
目前,我正在使用 forEach 遍历每个元素,如下所示:
carsLeft.forEach(carLeft => moveCarLeft(carLeft))
然后为了将元素向左移动一个空格,我输入一个 switch 语句来为其重新分配一个类:
switch(true) {
case carLeft.classList.contains('c1'):
carLeft.classList.replace('c1', 'c2')
break
case carLeft.classList.contains('c2'):
carLeft.classList.replace('c2', 'c3')
break
case carLeft.classList.contains('c3'):
carLeft.classList.replace('c3', 'c4')
break
}
我想知道是否有办法使用正则表达式将 switch 语句简化为如下所示:
carLeft.classList.replace(`c\d`, `c\d+`)
...或者可能是除使用正则表达式之外的另一种方法。感谢您花时间阅读本文。任何帮助将不胜感激。
I'd like to find a way to replace the token 'c1' with 'c2', replace 'c2' with 'c3', etc. using fewer lines of code.
Currently, I'm going through each element with forEach, like so:
carsLeft.forEach(carLeft => moveCarLeft(carLeft))
And then to move the element one space over to the left, I enter into a switch statement to reassign a class to it:
switch(true) {
case carLeft.classList.contains('c1'):
carLeft.classList.replace('c1', 'c2')
break
case carLeft.classList.contains('c2'):
carLeft.classList.replace('c2', 'c3')
break
case carLeft.classList.contains('c3'):
carLeft.classList.replace('c3', 'c4')
break
}
I was wondering if there is a way to use regular expressions to simplify the switch statement into something like this:
carLeft.classList.replace(`c\d`, `c\d+`)
...or perhaps another way aside from using regular expressions. Thank you for taking the time to read this. Any help would be much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
for
循环:You could use a
for
loop: