JavaScript sup()无法正常工作

时间:2018-07-19 16:37:39

标签: javascript

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

2 个答案:

答案 0 :(得分:4)

请避免使用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向我指出这一点。

答案 1 :(得分:1)

.sup() method不会在适当位置修改字符串,它需要一个字符串并返回一个新字符串。

因此,不仅仅是运行它...

 ec[i + 1].sup();

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

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

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

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