如何在jsrender中检查数组null或为空

How to check array null or empty in jsrender?

本文关键字:null 数组 检查 jsrender      更新时间:2023-09-26

这是下面的我的代码

<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语句

如果您使用的是{{for data}},那么实际上不需要测试空/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

试试这个


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>