JS 学习笔记(一)常用的字符串去重方法

发布于 2021-04-02  2,102 次阅读


要求:从输入框中输入一串字符,按回车后输出去重后的字符串

方法一:

<body>
    <input type="text" id="input" placeholder="请输入字符串">
    <p id="p1"></p>
</body>
<script>
    document.onkeydown = function (e) {
        var ev = window.event || e;
        var code = ev.keyCode || ev.which || ev.charCode;
        if (code == 13) {
            var str = document.getElementById("input").value
            console.log(str)
            var str2 = ''
            for (var i = 0; i < str.length; i++) {
                if (str2.indexOf(str[i]) == -1) {
                    str2 += str[i]
                }
            }
            console.log(str2)
            document.getElementById('p1').innerText = "去重后的字符为:" + str2
        }
    }

</script>

方法二:

<body>
    <input type="text" id="input" placeholder="请输入字符串">
    <p id="p1"></p>
</body>
<script>
    document.onkeydown = function (e) {
        var ev = window.event || e;
        var code = ev.keyCode || ev.which || ev.charCode;
        if (code == 13) {
            var str = document.getElementById("input").value
            console.log(str)
            var str2 = ''
            for (var i = 0; i < str.length; i++) {
                if (str2.search(str[i]) == -1)
                    str2 += str[i];
            }
            console.log(str2)
            document.getElementById('p1').innerText = "去重后的字符为:" + str2
        }
    }
 </script>

运行结果:
在这里插入图片描述


活的像诗一样