Javascript:将输入数值插入最接近的数字变量数组onchange

时间:2017-11-04 01:12:20

标签: javascript arrays

我需要在" 41"中插入用户输入数字值。 var value = getClosestNum( 41 ,intarray);。

我知道" 41"需要从输入中调用名称或id,但是生锈的Javascript尝试似乎总是以= 1结果。我已经尝试了几个getDocument,getID变体,子函数等,但没有成功。

理想情况下,通过在输入字段上使用onChange而不重新加载页面,结果将是即时的。

是的,以后必须使用JavaScript才能合并。

    <html>
    <head>
    <title>Find nearest value in javascript</title>
    <script language="javascript">
    // big array to come, example numbers
    var intarray=[1,2,3,5,7,9,11,33,40,42,44,55,66,77,88];
    // Now this function used to find out the close value in array for given number
    function getClosestNum(num, ar)
    {
        var i = 0, closest, closestDiff, currentDiff;
        if(ar.length)
        {
            closest = ar[0];
            for(i;i<ar.length;i++)
            {           
                closestDiff = Math.abs(num - closest);
                currentDiff = Math.abs(num - ar[i]);
                if(currentDiff < closestDiff)
                {
                    closest = ar[i];
                }
                closestDiff = null;
                currentDiff = null;
            }
            //returns first element that is closest to number
            return closest;
        }
        //no length
        return false;
    }
    </script>
    </head>
    <body>

        <form>
            <input type="number" id="test" name="test" onChange="?">
        </form>

    <script language="javascript">
    document.write("Array: "+intarray+"<br>");
    document.write("Value to find 41 <br>");

    // CODE TO CHANGE "41" to id or named input
    // 41 to reference input field

    var value=getClosestNum(41,intarray);

    document.write("Response Received "+value);
    </script>
    </body>
    </html>

2 个答案:

答案 0 :(得分:0)

你在每个循环中都没有对closestDiff的引用,你需要在整个循环中保留该值并在diff减少时更新它。

function getClosestNum(num, arr) {
    var closest;
    if (arr.length > 0) {
        closest = arr[0];
        var diff = Math.abs(arr[0] - num);
        for (var i = 1; i < arr.length; i++) {
            var currentDiff = Math.abs(arr[i] - num);
            if (diff > currentDiff) {
                closest = arr[i];
                diff = currentDiff;
            }
        }
    }
    return closest;
}

答案 1 :(得分:0)

据我了解,您正在尝试使用input元素取一个数字,并且您希望从数组中返回最接近该输入的数字。

我注册了一个触发“&#39;输入”的功能。事件。试试这个:

HTML

添加以下元素以查看函数的输出。您可以稍后将其重定向到您需要的任何位置。

<p id="output"></p>

的JavaScript

// wrap in an onload function to ensure 
// that the elements exist before searching for them
window.onload = () => {

    // cache of elements on the page you want to use
    const testInputElement = document.getElementById('test');
    const outputElement = document.getElementById('output');

    // create a function that will fire whenever input is received
    testInputElement.addEventListener('input', (event) => {
        outputElement.innerHTML = getClosestNum(event.target.value, intarray);
    })
};

onInput vs addEventListener('input')

onInput直接添加到元素内的HTML并不像通过addEventListener()以编程方式注册函数那样安全。如果你有一个名为handleInput()的函数,只需将该名称作为参数传递给addEventListener,就像这样

addEventListener('input', handleInput);

包含更改的代码

 <html>
<head>
<title>Find nearest value in javascript</title>
<script language="javascript">
// big array to come, example numbers
var intarray=[1,2,3,5,7,9,11,33,40,42,44,55,66,77,88];
// Now this function used to find out the close value in array for given number
function getClosestNum(num, ar)
{
    var i = 0, closest, closestDiff, currentDiff;
    if(ar.length)
    {
        closest = ar[0];
        for(i;i<ar.length;i++)
        {           
            closestDiff = Math.abs(num - closest);
            currentDiff = Math.abs(num - ar[i]);
            if(currentDiff < closestDiff)
            {
                closest = ar[i];
            }
            closestDiff = null;
            currentDiff = null;
        }
        //returns first element that is closest to number
        return closest;
    }
    //no length
    return false;
}
</script>
</head>
<body>

    <form>
        <input type="number" id="test" name="test" onChange="?">
    </form>
    <p id="output"></p>

<script language="javascript">
document.write("Array: "+intarray+"<br>");
document.write("Value to find 41 <br>");

// CODE TO CHANGE "41" to id or named input
// 41 to reference input field

var value=getClosestNum(41,intarray);

document.write("Response Received "+value);

// wrap in an onload function to ensure that the elements exist before searching for them
window.onload = () => {
    // cache of elements on the page you want to use
    const testInputElement = document.getElementById('test');
    const outputElement = document.getElementById('output');
    // create a function that will fire whenever input is received
    testInputElement.addEventListener('input', (event) => {
        outputElement.innerHTML = getClosestNum(event.target.value, intarray);
    })
};
</script>
</body>
</html>
相关问题