我有一个 ajax jquery 函数,它使用包含标签和值的每个元素填充数组:
var accountOptions = new Array();
$.ajax({
type: "GET",
url: apiUrl+"/Accounts/GetDropdown",
async: false,
success:
function (response) {
$.each(response.Data, function (i, item) {
accountOptions.push({ label: item.Number, value: item.Id })
});
}
});
这个函数工作正常,但我需要检查该数组中是否存在标签,但找不到如何执行此操作。我尝试了这个函数,但它检查数组以查看值是否存在而不是标签。
if ($.inArray(account, accountOptions) == -1)
{
$(this).addClass("validation-error");
alert("This account does not exist.");
}
感谢任何帮助。
最佳答案
您可以使用 jquery grep这会使用您设置的任何过滤器创建一个新数组。如果长度>0则它存在。
var array=[{'label':'one','value':'two'},{'label':'other','value':'more'},{'label':'foo','value':'bar'}];
var matches=$.grep(array,function(n){
return n.label=='foo';
});
if(matches.length==0)
alert('this account does not exist');
else
alert('this account exists');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 检查 Javascript 数组中是否存在标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33309877/