2017-02-10 185 views
-1

有人可以解释为什么行Logger.log("%s EQUALS %s",col1[i],col2[i]);永远不会被调用吗?林新Javascript,但基于this SO post我使用正确的运算符在if声明比较。值保证是整数,或者是一个空单元格,如果这有所作为。Javascript等于比较不起作用

function SetFilter(){ 
    var first_row_to_hide=4; 
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); 
    var maxrows=sheet.getMaxRows(); 
    col1 = sheet.getRange(first_row_to_hide,3,maxrows,1).getValues();//getRange(row, column, numRows, numColumns) -- column: C 
    col2 = sheet.getRange(first_row_to_hide,4,maxrows,1).getValues();//column: D 
    for (var i = 1; i < col1.length; i++){ 
    Logger.log("%s ? %s",col1[i],col2[i]); 
    if (col1[i] === col2[i]){ 
    Logger.log("%s EQUALS %s",col1[i],col2[i]); 
    }//sheet.hideRows(i+first_row_to_hide); 
    } 
    Logger.log("DONE"); 
} 

在列1和示例值2:

col1 col2 Log output of '%s ? %s' 
1 2 [1.0] ? [2.0] 
1 1 [1.0] ? [1.0] 
0 0 [0.0] ? [0.0] 
0 1 [0.0] ? [0.0] 
4 5 [4.0] ? [5.0] 
+1

*〜是的,因为'COL1 [i]'和'col2 [i]'从不[相同](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity) – Phil

+1

什么被记录'%s? %s'? – Ryan

+0

请问您可以添加'col1 [i]'和'col2 [i]'的值。另外,严格的相等运算符需要两个操作数的类型相同。 – Agalo

回答

0

“setValues方法()” 具有2维阵列。所以,你的脚本通过改变

if (col1[i] === col2[i]){ 
Logger.log("%s EQUALS %s",col1[i],col2[i]); 
}//sheet.hideRows(i+first_row_to_hide); 

到: “有人能解释为什么行?是从来没有所谓的”

if (col1[i][0] === col2[i][0]){ 
Logger.log("%s EQUALS %s",col1[i],col2[i]); 
}//sheet.hideRows(i+first_row_to_hide); 
0

您使用的严格比较===如果操作数是相同类型的,并且内容是相同的(其中,对象是其是唯一的真正有关他们必须引用完全相同的对象)。

鉴于抽象比较==在比较之前将操作数转换为相同类型。

可能col1[i]col2[i]违反上述条件之一。 (在它们是对象的情况下,也==将返回false,除非它们引用同一个对象)

MDN Comparison operator documentation

+0

这很有道理,但它们都是整数列(请参阅上面我更新的示例)。我可以错过别的东西吗,还是我误解了你? – Rilcon42

+0

边注意,但它听起来很奇怪在技术上,没有整数 - 类型会显示为'数字'。您可以使用'typeof'运算符来检查变量的类型。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof – roger

+0

看起来你在上面的评论中解决了它! - 但检查类型可能有助于防止将来出现这种混淆。 – roger