我正在尝试编写一个接受字符串的脚本,每当有一个字母时,下一个数字都会被上标。为此,我将字符串拆分为一个数组并循环遍历它-每当我找到一个字母时,我都会在下一个数组元素上运行 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 tugh 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
// igning 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 yoeach
// ahead and modify the next value, you suld 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 向我指出这一点。
.sup()
metd不修改字符串,它接受一个字符串并返回一个新的字符串。
所以不只是运行它...
ec[i + 1].sup();
...您需要将其结果分配回您的字符串...
ec[i + 1] = ec[i + 1].sup();
但是,正如其他用户所指出的那样,该方法可能不应该再使用了,因为它被认为是“已弃用”,并且可能会被浏览器删除。幸运的是,它的替换非常简单,因为它所做的只是在字符串周围添加<sup>
和</sup>
,因此您可以重写没有它的行:
ec[i + 1] = '<sup>' + ec[i + 1] + '</sup>';
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(34条)