JavaScript打破每个循环

时间:2016-08-04 09:41:19

标签: javascript jquery performance

function hellofunction(arrObj, val){
    $.each(arrObj,function(k,v){
        if(arrObj[k]["EMP_NO"] == val){
            return arrObj[k]["EMP_NAME"];
        }
    });
}

// Call function
var kaka = hellofunction(data["OUT_REC"], "roth_kakvey");

console.log("=====:"+kaka);

输出=“欠精简”

请帮助我,为什么它总是输出=“Underfine”?

1 个答案:

答案 0 :(得分:1)

$.each(arrObj,function(k,v){
        if(arrObj[k]["EMP_NO"] == val){
            return arrObj[k]["EMP_NAME"];  
           // does not return from the hellofunction.
           // Instead it returns from the function(k,v) i.e. the callback to each
        }
    });

所以要做到这一点:

function hellofunction(arrObj, val){
    var empName;
    $.each(arrObj,function(k,v){
        if(arrObj[k]["EMP_NO"] == val){
            empName = arrObj[k]["EMP_NAME"];
            return false; //returning from callback, works like break statement
        }
    });
    return empName;
}