javascript代码中的逻辑错误

时间:2015-06-17 14:09:09

标签: javascript jquery

我正在尝试编写一些逻辑来检查两个表中是否存在特定记录。 如果该行存在于任一表中,我想返回TRUE。

对于表A,当记录添加到表中时,id字段看起来像" 123"。 对于表B,相同的记录将具有" a123"的id。但是,我必须搜索记录的值是" row_123"。

这就是我现在的代码:

var checkForDuplicates = function(row_id) {

   return !!($('#existing_members').find('#' + row_id.replace('row_','')).length || $('#selected_users').find('#' + row_id.replace('row_','a').length) );

};

如果记录存在于任何一个表中,我希望函数返回true 但是,如果该语句应为false,则返回true。

我迄今为止所做的尝试 我一直在控制台里玩,以确保我的逻辑是正确的:

!!(1 || 0)  //returns true
!!(0 || 0)  //returns false
!!(0 || 1)  //returns true

我目前还在查看替换语句,以确保为find()提供正确的字符串。

但第二双眼睛确认我的逻辑是正确的将不胜感激。

由于

编辑1

使用Max的建议解决方案是:

  var checkForDuplicates = function(row_id) {
             var parts = row_id.split('_');
             var tableB = '#a'+ parts[1];
             var tableA = '#' + parts[1];
             return !!($('#existing_members').find(tableA).length || $('#selected_users').find(tableB).length);
 }

但是,正如Ankit指出的那样,我的原始代码中只有一个拼写错误。所以这将是我的最终答案/解决方案:

var checkForDuplicates(row_id) {
       return !!( $('#existing_members').find('#' + row_id.replace('row_', '')).length || $('#selected_users').find('#' + row_id.replace('row_','a')).length);
}

4 个答案:

答案 0 :(得分:1)

纠正了一些问题,以提高代码效率:

var checkforduplicates = function(row_id) {
   var id = row_id.split('_')[1];  // [ 'row', '123']
   return $('#'+id).length || $('#a'+id).length;
}
  • 不需要!!,因为operator ||会产生布尔结果(true或 假)
  • 使用$('#'+id)作为更高效的jQuery选择器
  • 删除了不必要的find(..)电话
  • 消除不必要的括号(有问题)

答案 1 :(得分:1)

您的代码在return语句结尾处有拼写错误

...'a').length));  //it returns object which always evaluates to true

应该是

...'a')).length);   

<强>样本

	var checkforduplicates = function(row_id){
     //row_id looks like "row_123"
	 return !!($('#tableA').find('#' + row_id.replace('row_','')).length || $('#tableB').find('#' + row_id.replace('row_','a')).length );
	
}
alert(checkforduplicates("row_123"));
<table id=tableA><tr><td id="123">123 ID</td></tr></table>
	<table id=tableA><tr><td id="a13">a13 ID</td></tr></table>

答案 2 :(得分:0)

I want the function to return true if the record exists in either table.

var checkForDuplicates = function(row_id) {
    row_id = row_id.substring(4); // 'row_123' -> '123'

    var table_A_row_id = row_id;
    var table_A_row_exists = $('#tableA').find('#' + table_A_row_id).length > 0;

    var table_B_row_id = 'a' + row_id;
    var table_B_row_exists = $('#tableB').find('#' + table_B_row_id).length > 0;

    return table_A_row_exists || table_B_row_exists;
};

答案 3 :(得分:-1)

当然,它会返回你想要的东西,因为你正在使用!!

!用于协商特定函数/变量的返回值,例如:

if(!var_x == false)

此示例仅在var_x为true时有效。 所以请注意避免!!;)

请改为使用一个!

相关问题