简体   繁体   中英

Javascript Uncaught TypeError: Cannot read property 'push' of undefined

It says 'Uncaught TypeError: Cannot read property 'push' of undefined' I feel im not intializing the array in the correct way please help.

var validationInfo = new Array();
var currentStep = 1;
validationInfo["step1"].push({ elementId: "txtsearchBar",       validateFunc: isEmpty });
validationInfo["step2"].push({ elementId: "txtdetails",         validateFunc: isEmpty });  
function isEmpty(element) {
    //alert(element);
    return $(element).val() == undefined || $(element).val() == "";
}
function isCurrentSubmissionValid(stepId) {
    var isOK = true;
    alert(validationInfo);
    for (var i = 0; i < validationInfo[stepId].length; i++) {
        var element = $("#" + validationInfo[i].elementId);
        var validationFunction = validationInfo[i].validateFunc;
        if (!validationFunction(element)) {
            element.addClass("has-error").removeClass("has-success");
            isOK = false;
        } else
        {
            element.addClass("has-success").removeClass("has-error");
        }
    }
    return isOK;
}

Create validationInfo as an Object not an Array

 var validationInfo = {step1: [], step2: [] }; validationInfo['step1'].push("haha"); validationInfo['step2'].push("hehe"); console.log(validationInfo)

In your loop, I believe you have to do similar change, for example:

validationInfo[stepId][i].elementId

assuming stepId is one of step1 or step2 . Wen you access validationInfo[i] , you are accessing keys like: 0, 1 ,2, etc in the validationInfo . Those are the indexes of your step1 or step2 arrays..

由于在javascript中使用push方法时无法传递密钥,因此您可以尝试一下。

validationInfo.push({ value: { elementId: "txtsearchBar", validateFunc: isEmpty }, index: 'step1'});

you should write define _this = this; in head, then replace all this of _this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM