Search code examples
javascriptjquerybackbone.js

TypeError: 'undefined' is not an object in Javascript


I have a piece of Javascript code that assigns string of values to a string array. Unfortunately if I try to add more than one string to the array, my UI simulator(which runs on JS code) closes unexpectedly. I have tried debugging but I cannot find anything. I am attaching that piece of code where the issue is. may be you guys could find some flaw? On the pop up button click the values I selcted on the UI should get stored in the array and I have a corressponding variable on the server side to handle this string array.

_popupButtonClick: function (button) {
                var solutions = this._stateModel.get('solutionName');
                var i;
                var solutionsLength = solutions.length;
                var selectedSolution = [solutionsLength];


                this.clearPopupTimer();
                if (button.position === StatusViewModel.ResponseType.Ok) {

                    for(i=0;i<solutionsLength;i++)
                    {
                        if(this._list.listItems[i].selected)
                        {
                            selectedSolution[i] = this._list.listItems[i].options.value;
                        }
                    }

                    this._stateModel.save({
                        selectedsolutions: selectedSolution,
                        viewResponse: StatusViewModel.ResponseType.Ok
                    });
                } else {
                    this._stateModel.save({
                        viewResponse: StatusViewModel.ResponseType.Cancel
                    });
                }

            }

Solution

  • Change

    var selectedSolution = [solutionsLength];
    

    to

    var selectedSolution = [];
    

    This makes your array have an extra item that might be causing a crash.

    Also,

    you have an

    if(this._list.listItems[i].selected)
    {
        selectedSolution[i] = this._list.listItems[i].options.value;
    } 
    

    But no corresponding else, so your array has undefined values for i which are not entering the if.

    Maybe adding an empty string might solve it:

    if(this._list.listItems[i].selected)
    {
        selectedSolution[i] = this._list.listItems[i].options.value;
    } 
    else
    {
        selectedSolution[i] = "";
    }