如何在jsrender中检查数组是否为空?

How to check array null or empty in jsrender?

下面是我的代码

<script type="text/javascript">
   
  var test1 = {
    "type" : "success",
    "code" : "600",
    "data" : [ ]
   };
  
  var template = $.templates("#template");
  var htmlOutput = template.render(test1);
  $("#billListBox").html(htmlOutput);
  
  function billButtonOnClick(searchBillId,isComeFromBillClick,billDiv){
   console.log(searchBillId);
   console.log(isComeFromBillClick);
   console.log(billDiv);
  }

 </script>
<div id="billListBox"></div> 

我想在jsrender中检查数据是空的还是null?如何检查?

你不能检查一下 test1.data && test1.data.length > 0

jsrender 也有 if/else 语句

试试这个

<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre><code>var test1 = {
    "type" : "success",
    "code" : "600",
    "data" : [ ]
   };

//check condition if array is empty or not
if(jQuery.isEmptyObject(test1.data)){
 alert("array is empty");
}else{
 alert("array is not empty");
}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

如果您正在使用 {{for data}},那么您实际上不需要测试 empty/null(无论是在代码中还是通过包装在 {{if}}...{{/if}} 中)。

你可以简单地写

{{for data}}
    ...
{{/for}}

即使它为空或 null 也能正常工作 - 它不会为该块呈现任何内容。

或者,如果您愿意,可以使用

{{for data}}
    ...
{{else}}
    output this if data is empty or null
{{/for}}

它会输出你想要的 null/empty 情况下的任何内容。

http://www.jsviews.com/#fortag