我正在尝试编写一个包含字符串的脚本,并且每当有字母时,下一个数字就是上标。为此,我将字符串拆分为一个数组并循环遍历-每当找到字母时,我都会在下一个数组元素上运行sup()。
JS
var ec = "1s2 2s4".split("");
for (var i = 0; i < ec.length; i++) {
if (ec[i].match(/[a-z]/i)) {
ec[i + 1].sup();
}
}
但是当我这样做时,我运行sup()的数字没有任何反应。为什么是这样?
JSfiddle:http://jsfiddle.net/yxj143az/7/
最佳答案
只是避免使用sup,这是如何完成此操作的快速示例:
var ec = "1s2 2s4".split("");
for (var i = 0; i < ec.length; i++) {
if (ec[i].match(/[a-z]/i)) {
// I removed the call to sup, even though it is only deprecated
// and has been for awhile it is still accessible. Feel free to
// use it if you would like, i just opted not to use it.
// The main issue with your code was this line because you weren't
// assigning the value of your call to sup back to the original variable,
// strings are immutable so calling on a function on them doesn't change
// the string, it just returns the new value
ec[i + 1] = '<sup>' + ec[i + 1] + '</sup>';
// if you want to continue to use sup just uncomment this
// ec[i + 1] = ec[i + 1].sup();
// This is a big one that I overlooked too.
// This is very important because when your regex matches you reach
// ahead and modify the next value, you should really add some checks
// around here to make sure you aren't going to run outside the bounds
// of your array
// Incrementing i here causes the next item in the loop to be skipped.
i++
}
}
console.log(ec.join(''));
编辑/更新基于评论中的一些有效反馈,我回去评论了答案,以确切说明我所做的更改以及原因。非常感谢@IMSoP向我指出了这一点。
关于javascript - JavaScript sup()无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51427882/