繁体   English   中英

JavaScript sup()无法正常工作

[英]Javascript sup() not working

我正在尝试编写一个包含字符串的脚本,并且每当有字母时,下一个数字就是上标。 为此,我将字符串分割成一个数组并循环遍历-每当我找到一个字母时,就在下一个数组元素上运行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(/[az]/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向我指出这一点。

.sup()方法不会在适当位置修改字符串,它接受一个字符串并返回一个新字符串。

因此,不只是运行它而已...

 ec[i + 1].sup();

...您需要将其结果分配回您的字符串...

 ec[i + 1] = ec[i + 1].sup();

但是,正如其他用户所指出的那样,该方法可能不应再使用,因为它被认为“已弃用”,并且可能会被浏览器删除。 幸运的是,替换非常简单,因为它所做的只是在字符串周围添加<sup></sup> ,因此您可以不使用它而重写该行:

 ec[i + 1] = '<sup>' + ec[i + 1] + '</sup>';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM