0

I'm looping through DOM elements when a certain button is clicked. I've attached the class finish-proc to the button, so when clicked will activate this function:

<script>
    $(document).on('click', '.finish-proc', function () {
        var communities = [];

        var $this, $thisDay, input, inputDay, text, textDay, obj, objDay;

        $('.panel-default').each(function (i) {
            var maxPeople = '.' + $(this).attr('data-community') + '-max-people';
            var dayInfoRow = '.' + $(this).attr('data-community') + '-day-info';
            obj = {};
            obj["maxPeople"] = $(maxPeople).val();

            var daysArrayInLoop = [];

            $(dayInfoRow).each(function (j) {
                var objDay = {};

                var dayString = '.' + $(this).attr('data-community') + '-day-' + (j + 1);
                var dayStringStart = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-start';
                var dayStringEnd = '.' + $(this).attr('data-community') + '-day-' + (j + 1) + '-end';

                objDay["dayString"] = $(dayString).val();
                objDay["dayStringStart"] = $(dayStringStart).val();
                objDay["dayStringEnd"] = $(dayStringEnd).val();

                daysArrayInLoop.push(objDay);
            }

            obj["dayArray"] = daysArrayInLoop;

            communities.push(obj);
        }
   }
</script>

This code is breaking on the line:

daysArrayInLoop.push(objDay);

With the error:

daysArrayInLoop.push is not a function

Can anyone tell me why this is?

EDIT - I've tried to alter the var daysArrayInLoop = []; to var daysArrayInLoop = {};, still getting the same error

LatentDenis
  • 2,839
  • 12
  • 48
  • 99

1 Answers1

2

Try This code define array after push in object

var daysArrayInLoop = new Array();
    daysArrayInLoop.push(obj);
  • That did it. I don't understand how that worked rather than placing `var daysArrayInLoop = [];` – LatentDenis May 30 '17 at 06:18
  • 1
    `function Array() { this.is = 'SPARTA'; } var a = new Array(); var b = []; alert(a.is); // => 'SPARTA' alert(b.is); // => undefined a.push('Woa'); // => TypeError: a.push is not a function b.push('Woa'); // => 1 (OK)` new Array() is create a new runtime array. No extra processing necessary at all [link](https://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar) – Parin Patel May 30 '17 at 12:53
  • Thanks for the explanation and link reference! I understand now. :) – LatentDenis May 30 '17 at 13:59