比较基于长度两个数组:跳过空值 [英] compare two arrays based on length: skip empty values

查看:230
本文介绍了比较基于长度两个数组:跳过空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个输入的表单(甚至可以更多),用户可以把一个数字或没有。唯一的规则是,如果你把一个输入一个数字,如果相同数量是另一个输入(无重复),你不能提交。只要你想,你可以与许多空的输入提交。

要验证输入我比较的所有与唯一的值相同的数组输入的数组的长度。如果它们具有相同的长度它的确定。
我需要改善我的code因为现在它只能如果用户输入的所有输入字段。如果某些输入都是空的,他们用独特的价值在数组中认为它们都具有作为值。所以,如果用户输入一个号码我将得到数组长度是4和阵列独特的是2,但它应该是1和1(跳过空白项目)。

我想使用拼接()改编,但是这是要做到这一点验证的最佳方法?
**编辑:我申请的剪接,但如果数组为('1','','')我的code给我('1',''),而不是仅仅(1)我期望。 .. **这是因为剪接删除项目并改变数组长度,这样的循环指向错误的索引。
任何想法?
HTML:

 < D​​IV CLASS =经济特区形式>
    <&字段集GT;
        <传奇> Messaggi inclusi< /传说>
        < D​​IV CLASS =percheckbox>
            <输入类=checkseq类型=复选框值=1NAME =messaggio [0]>
            PROVA迪messaggio车scorre< BR>
            <标签> ORDINE:LT; /标签>
            <输入类=序列类型=文本名称=ORDINE [0]MAXLENGTH =2大小=2>
        < / DIV>        < D​​IV CLASS =percheckbox>
            <输入类=checkseq类型=复选框VALUE =3NAME =messaggio [1]>
            Titoli迪电影< BR>
            <标签> ORDINE:LT; /标签>
            <输入类=序列类型=文本名称=ORDINE [1]MAXLENGTH =2大小=2>
        < / DIV>        < D​​IV CLASS =percheckbox>
            <输入类=checkseq类型=复选框VALUE =6NAME =messaggio [2]>
            PROVA一德图fisso< BR>
            <标签> ORDINE:LT; /标签>
            <输入类=序列类型=文本名称=ORDINE [2]MAXLENGTH =2大小=2>
        < / DIV>
        < BR风格=明确:既;>
    < /字段集>
< / DIV>

JavaScript的:

 函数uniqueArray(ARR){
    返回$ .grep(ARR,函数(V,K){
        返回$ .inArray(V,ARR)=== K表;
    });
}$(文件)。就绪(函数(){
    $('#invia')。点击(函数(五){
        亦即preventDefault();
        。VAR ARR = $(序列),地图(函数(){$返回(本).VAL();})的toArray()。
        VAR空= $(序列)。过滤器(函数(){
            返回THIS.VALUE ==;
        })
    对于(指数= 0;指数 - LT; arr.length ++指数){
        如果(ARR [指数] ==''){
            new_arr = arr.splice([指数],1);
        }
        的console.log(ARR);
    }        如果(empty.length == $('序列')。长){
            警报(非海scelto alcun messaggio每1L工作流程Correggi每procedere。');
        }
        否则,如果(uniqueArray(ARR)。长度!= $('序列')。长){
            的console.log(uniqueArray(ARR));
            警报('慈索诺VOCI重复内拉SEQUENZA Correggi每procedere。');
        }
        否则,如果($('#dt_from)VAL()=='__ / __ / __ ____ __'){
            警报('Scegli数据E ORA迪inizio validit \\ u00E0每1L工​​作流');
        }
        否则,如果($('#dt_to)VAL()=='__ / __ / __ ____ __'){
            警报('Scegli数据E ORA迪精细validit \\每1L工作流程u00E0');
        }
        其他{
            ajaxSubmit会();
        }
    });
});


解决方案

使用哈希你遍历跟踪值。这个例子只是返回真正,但你也可以扫描整个数组,并返回重复的值。

 函数uniquifyArray(元){
    变种看出= {};
    isUnique设置变种= TRUE;
    / *迭代向后因为作为元素被删除数组的长度将改变* /
    对于(VAR I = ary.length;我 - ;){
        / *删除空白/不确定* /
        如果(typeof运算元[I] ===未定义||元[I] ===''){
            ary.splice(I,1);
        }其他{
            / *检查,如果这个值已经看到* /
            如果(进制[i]于看到){
                = isUnique设置虚假的;
                ary.splice(I,1);
            }其他{
                看到[元[I] = TRUE;
            }
        }
    }
    进制= ary.sort();
    isUnique设置返回;
}变种测试= ['1','2','','','3','4','1'];
uniquifyArray(试验); //返回假,测试= ['1','2','3','4']测试= ['1','2','','']
uniquifyArray(试验); //真,测试= ['1','2']

I have a form with 4 input (can be even many more) where the user can put a number or nothing. The only rule is that if you put a number in a input you cannot submit if the same number is in another input (no duplicates). You can submit with as many empty input as you want.

To validate the input I compare the length of the array of all the inputs with the same array with only unique values. If they have the same length it's ok. I need to improve my code because now it works only if the user enters all the input fields. If some inputs are empty they are considered in the array with unique value as they all have "" as a value. So, if the user enters just one number I will get that array length is 4 and array unique is 2 but it should be 1 and 1 (skipping the blank items).

I was thinking about using splice() on arr, but is this the best way to do this validation? **EDIT: I applied splice BUT if the array is ('1','','') my code gives me ('1','') instead of just (1) as I'd expect... ** This is because splice remove the item and change array length so that the for loop point to the wrong index. Any idea? HTML:

<div class="sez-form">
    <fieldset>
        <legend>Messaggi inclusi</legend>
        <div class="percheckbox">
            <input class="checkseq" type="checkbox" value="1" name="messaggio[0]">
            Prova di messaggio che scorre<br>
            <label>Ordine: </label>
            <input class="seq" type="text" name="ordine[0]" maxlength="2" size="2">
        </div>

        <div class="percheckbox">
            <input class="checkseq" type="checkbox" value="3" name="messaggio[1]">
            Titoli di film<br>
            <label>Ordine: </label>
            <input class="seq" type="text" name="ordine[1]" maxlength="2" size="2">
        </div>

        <div class="percheckbox">
            <input class="checkseq" type="checkbox" value="6" name="messaggio[2]">
            Prova a testo fisso<br>
            <label>Ordine: </label>
            <input class="seq" type="text" name="ordine[2]" maxlength="2" size="2">
        </div>
        <br style="clear: both;">
    </fieldset>
</div>

JAVASCRIPT:

function uniqueArray(arr) {
    return $.grep(arr,function(v,k) {
        return $.inArray(v,arr) === k;
    });
}

$(document).ready(function() {
    $('#invia').click(function(e) {
        e.preventDefault();
        var arr = $(".seq").map(function(){ return $(this).val(); }).toArray();
        var empty = $(".seq").filter(function() {
            return this.value == "";
        })
    for (index = 0; index < arr.length; ++index) {
        if (arr[index]=='') {
            new_arr = arr.splice([index],1);
        }
        console.log(arr);
    }

        if(empty.length == $('.seq').length) {
            alert('Non hai scelto alcun messaggio per il workflow. Correggi per procedere.');
        }
        else if(uniqueArray(arr).length != $('.seq').length) {
            console.log(uniqueArray(arr));
            alert('Ci sono voci duplicate nella sequenza. Correggi per procedere.');
        }
        else if($('#dt_from').val()=='__/__/____ __:__') {
            alert('Scegli data e ora di inizio validit\u00E0 per il workflow');
        }
        else if($('#dt_to').val()=='__/__/____ __:__') {
            alert('Scegli data e ora di fine validit\u00E0 per il workflow');
        }
        else {
            ajaxSubmit();
        }
    });
});

解决方案

Use a hash to track values as you iterate. This example simply returns true or false, but you could also scan the entire array and return the repeated values.

function uniquifyArray(ary) { 
    var seen = {};
    var isUnique = true;
    /* iterate backwards since the array length will change as elements are removed */
    for (var i=ary.length; i--;) {
        /* remove blank/undefined */
        if (typeof ary[i] === 'undefined' || ary[i] === '') {                
            ary.splice(i,1);
        } else {   
            /* check if this value has already been seen */
            if (ary[i] in seen) { 
                isUnique = false;
                ary.splice(i,1);
            } else { 
                seen[ary[i]]=true;   
            }
        }
    }
    ary = ary.sort();
    return isUnique;
}

var test = [ '1','2','','','3','4','1' ];
uniquifyArray(test); // returns false, test = [ '1','2','3','4' ]

test = [ '1','2','','' ]
uniquifyArray(test); //true, test = ['1','2']

这篇关于比较基于长度两个数组:跳过空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆