jQuery.Deferred 异常:无法读取属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38533771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:11:21  来源:igfitidea点击:

jQuery.Deferred exception: Cannot read property

jquery

提问by L.Clark

var arr = [{
    value: 'a'
}];
var getTest = function() {
    jQuery.each(arr, function(i, val) {

        if (val.value == "a") {
            return val;
        }
    });
}

alert(getTest().value);

jquery-3.1.0.js:3793 Uncaught TypeError: Cannot read property 'value' of undefined

jquery-3.1.0.js:3793 未捕获的类型错误:无法读取未定义的属性“值”

采纳答案by Aleksandar ?oki?

var arr = [{
    value: 'a'
}];
var getTest = function() {
    var toRet;
    jQuery.each(arr, function(i, val) {
        if (val.value == "a") {
            toRet = val;
        }
    });
    return toRet;
}

alert(getTest().value);

jQuery.eachis actually a function and you are returning value there and not to your function getTest(). This is working solution.

jQuery.each实际上是一个函数,你在那里返回值而不是你的函数getTest()。这是有效的解决方案。