关于javascript例程需要帮助

时间:2014-12-17 11:37:53

标签: javascript

我有两个例行的一个返回下拉值作为数组,另一个返回基于给定输入的数组中的最高接近值。问题是函数closest()无效,我也无法理解。

这里是完整代码

$(document).ready(function () {

    //var array = [00, 05, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
    //var number = 05;
    //alert(closest(number, array)); // display output here


    function closest(num, arr) {
        var next = Math.max.apply(Math, arr);


        for (var val = 0; val < arr.length; val++) {
            if (arr[val] >= num && arr[val] < next) next = arr[val];
        }

        curr = next;

        curr = (curr >= 10) ? curr : '0' + curr; //If result is 5, to display '05' instead of '5'
        return curr;
    }


    function cboValueToArray(targetid) {
        var $target = $("select[id*=" + targetid + "] option");
        var results = [];
        $target.each(function () {
            var val = $(this).val();
            if (val !== '') results.push(val);
        });
        //alert(results.toString());
        return results;
    }
    alert(closest(09,cboValueToArray('DropDownList1').toString()));

});

1 个答案:

答案 0 :(得分:0)

你不能像这样构造一个数组:

var cboarry = '[' + cboValueToArray('DropDownList1') + ']';

无论发出什么警报,这都会产生一个字符串。 您可以通过以下方式查看:

console.log(typeof cboarry); //string

此外,在您的closest函数中,您引用的变量number应为num

更正后的代码:

function closest(num, arr) {
    var next = Math.max.apply(Math, arr);
    for (var val = 0; val < arr.length; val++) {
        if (arr[val] >= num && arr[val] < next) next = arr[val];
    }

    curr = next;
    curr = (curr >= 10) ? curr : '0' + curr; 
    return curr;
}


function cboValueToArray(targetid) {
    var $target = $("select[id*=" + targetid + "] option");
    var results = [];
    $target.each(function () {
        var val = $(this).val();
        if (val !== '') results.push(val);
    });

    return results;
}

var cboarry = cboValueToArray('DropDownList1');
alert(closest(9, cboarry));