0

I have JavaScript array and fill it data from mvc modal:

<script type="text/javascript">
    var letterOfResponsibilityNotes = Array(0);

    @if (Model.Step2.SelectedCountryList.Count != 0)
    {
        foreach (var item in Model.Step2.SelectedCountryList)
        {
            <text>letterOfResponsibilityNotes["@item.Code"]='@item.LetterOfResponsibilityNote'</text>
        }
    } 

Then I try to get letterOfResponsibilityNotes array length:

if ($(letterOfResponsibilityNotes).length > 0)
{ ... }

But I get always lenth = 0, despite I see the data in FireBug.

Thanks!

IFrizy
  • 1,705
  • 4
  • 17
  • 33

3 Answers3

1

That's because @item.Code is not a number.

var a = new Array(0);
a["test1"] = "test1";
a["test2"] = "test2";

// a.length is still 0 - although it has contents

a["3"] = "try a number";

// now a.length == 4, which is highest number subscript key + 1
// unfortunately that is how JS arrays work

To find length of your array see Length of a javascript associative array

Community
  • 1
  • 1
YK1
  • 7,327
  • 1
  • 21
  • 28
0

Try this:

first initialize the as follow in JavaScript.

var letterOfResponsibilityNotes = new Array();

console.log(letterOfResponsibilityNotes.length);

if(letterOfResponsibilityNotes.length > 0)
{

}

if array have any value it display length of array.
Mr.G
  • 3,413
  • 2
  • 16
  • 20
0

delete '$' on IF.

if ((letterOfResponsibilityNotes).length > 0)
{ ... }

with $ i have this fail

Uncaught ReferenceError: $ is not defined

TiGreX
  • 1,602
  • 3
  • 26
  • 41
  • put a 'sneak' (sorry, i don't know the name on English of this XD) on each turn of loop with `letterOfResponsibilityNotes.length` to control if the input data on array are correct – TiGreX Dec 14 '13 at 10:44