使用 indexOf 在数组中查找项目
Find item in array with indexOf
我对 'indexOf' 有疑问。当我在参数中传递一个数值时,它有效,但不适用于变量:
$.ajax({
url: 'bdd.php',
type: 'POST',
data: {'jsonNomCommune': jsonNomCommune, 'client': client},
success: function(data) {
data = JSON.parse(data);
listClients= data.clients;
listProspects = data.prospects;
$('#tableCSV tbody tr ').each(function(){
var id = $(this).attr('id');
id=id.substring(4);
if (listClients.indexOf(id) > -1){
$(this).css("background-color","red");
}
if (listProspects.indexOf(id) > -1){
$(this).css("background-color","blue");
}
});
}
});
listProspects 和 listClients 是数值数组。例如,27 在 listClients 中,所以当 id=27 时,"listClients.indexOf(id) > -1" 应该起作用,但它不起作用。当我写:“(listClients.indexOf(27)> -1)”它有效。
问题出在哪里??
27
和"27"
不同。
尝试将 id 解析为整数:
listClients.indexOf(+id) //note, its parsing
或:
listClients.indexOf(parseInt(id, 10))
您应该将 $(this).attr('id')
的值转换为数字。
所以应该是var id = Number($(this).attr('id'));
使用 parseInt() 方法将 id 转换为整数
我对 'indexOf' 有疑问。当我在参数中传递一个数值时,它有效,但不适用于变量:
$.ajax({
url: 'bdd.php',
type: 'POST',
data: {'jsonNomCommune': jsonNomCommune, 'client': client},
success: function(data) {
data = JSON.parse(data);
listClients= data.clients;
listProspects = data.prospects;
$('#tableCSV tbody tr ').each(function(){
var id = $(this).attr('id');
id=id.substring(4);
if (listClients.indexOf(id) > -1){
$(this).css("background-color","red");
}
if (listProspects.indexOf(id) > -1){
$(this).css("background-color","blue");
}
});
}
});
listProspects 和 listClients 是数值数组。例如,27 在 listClients 中,所以当 id=27 时,"listClients.indexOf(id) > -1" 应该起作用,但它不起作用。当我写:“(listClients.indexOf(27)> -1)”它有效。
问题出在哪里??
27
和"27"
不同。
尝试将 id 解析为整数:
listClients.indexOf(+id) //note, its parsing
或:
listClients.indexOf(parseInt(id, 10))
您应该将 $(this).attr('id')
的值转换为数字。
所以应该是var id = Number($(this).attr('id'));
使用 parseInt() 方法将 id 转换为整数