我有JavaScript数组并从mvc模式填充数据:
<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>
}
}
<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>
}
}
然后我尝试获得数组长度:
letterOfResponsibilityNotes
但我总是if ($(letterOfResponsibilityNotes).length > 0)
{ ... }
,尽管我在FireBug中看到了数据。
谢谢!
答案 0 :(得分:1)
那是因为@item.Code
不是数字。
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
要查找数组的长度,请参阅Length of a javascript associative array
答案 1 :(得分:0)
试试这个:
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.
答案 2 :(得分:0)
在IF上删除'$'。
if ((letterOfResponsibilityNotes).length > 0)
{ ... }
使用$ i将此失败
未捕获的ReferenceError:$未定义