用逗号将字符串拆分为数字,然后打印最终会跳过 1 个 y 值

Splitting string into numbers by commas and then printing ends up skipping 1 y-value

这段代码是将x和y作为输入,用逗号分隔字符串,将它们转换为整数,然后打印出字符串。

<body>
    x: <input id="xv"> <br/>
    y: <input id="yv">
    <br/>
    <div id="results">
    <button onclick="action()">Go</button>
    </div>

    <script>

        // javascript
        var action = function(){

            // separate by commas and place into array
            var xvs = document.getElementById("xv").value.split(",");
            var yvs = document.getElementById("yv").value.split(",");

            // convert to an integer
            for(var i=0, j=xvs.length; i<j; i++){
                xvs[i] = parseInt(xvs[i]);
                yvs[i] = parseInt(yvs[i]);
            }

            // print out results
            document.getElementById("results").innerHTML = xvs + "<br/>" + yvs;
        }

    </script>
</body>

您会期望它打印出与输入完全相同的副本。但是,相反,我得到了这个结果:

Input:
62,64,64,65,65,65,65,66,66,66,66,66,66,66,67,67,67,68,69,69 
62,63,63,64,66,65,64,67,67,63,64,68,65,66,66,65,68,68.69,70 

Output:
62,64,64,65,65,65,65,66,66,66,66,66,66,66,67,67,67,68,69,69
62,63,63,64,66,65,64,67,67,63,64,68,65,66,66,65,68,68,70,NaN

有人知道这是怎么回事吗?

这是一个 jsfiddle link:https://jsfiddle.net/zs65x2e3/

请注意,如果不将其放入单独的 <script> 标签中,代码将不起作用,因为 action() 被视为 undefined

您的输入有误,

旧:

62,64,64,65,65,65,65,66,66,66,66,66,66,66,67,67,67,68,69,69 
62,63,63,64,66,65,64,67,67,63,64,68,65,66,66,65,68,68.69,70 

固定:

62,64,64,65,65,65,65,66,66,66,66,66,66,66,67,67,67,68,69,69 
62,63,63,64,66,65,64,67,67,63,64,68,65,66,66,65,68,68,69,70 

你用的是句点而不是逗号。

错误不是因为句号。循环有问题。 你是 运行 x 输入长度的循环。如果 y 输入的输入少于 x 输入,那么对于 y 的剩余迭代,您将得到 NaN。 在您的示例输入中,周期导致输入的长度小于 1,因此您最后得到 1 NaN。