代码之家  ›  专栏  ›  技术社区  ›  user7548189

javascript sup()不工作

  •  1
  • user7548189  · 技术社区  · 7 年前

    我正在写一个需要字符串的脚本,每当有字母时,下一个数字就是上标的。为此,我将字符串拆分成一个数组并循环遍历它——每当我找到一个字母,我就对下一个数组元素运行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()的数值不会发生任何变化。这是为什么?

    J小提琴: http://jsfiddle.net/yxj143az/7/

    2 回复  |  直到 7 年前
        1
  •  4
  •   Stephen P    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向我指出这一点。

        2
  •  1
  •   IMSoP    7 年前

    这个 .sup() method 不在适当位置修改字符串,它将获取一个字符串并返回一个新字符串。

    所以与其只是运行它…

     ec[i + 1].sup();
    

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

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

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

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