2016-07-26 76 views
0

我想實現2個字符串之間的區分大小寫比較。 這是我迄今所做的,它不工作這麼好javascript比較字符串大小寫敏感

function compare(x,y){ 
    for (var i = 0; i < Math.min(x.length, y.length); i++){ 
    var xc = x[i]; 
    var yc = y[i]; 
    if (xc == yc) 
    continue; 
    var xclow = x.toLowerCase(); 
    var yclow = y.toLowerCase(); 
    if (xclow == yclow) 
     return xc < yc ? -1 : 1 
    else 
     return xclow < yclow ? -1 : 1; 

} 

}

如果即時通訊做console.log(compare("Kk","kk"));我得到-1不如預期,但如果我做console.log(compare("Kka","kk"));我是得到1,我不知道爲什麼。

+0

壓縮?比較? – Bergi

+1

如果你想讓它成爲case * sensitive *,你是否正在做'toLowerCase'? – Bergi

+0

比較當然,對不起拼寫錯誤 – styx

回答

1

當時有兩輛錯字,你寫x.toLowerCase();代替xc.toLowerCase();y.toLowerCase();而不是yc.toLowerCase();

function compare(x, y) { 
    for (var i = 0; i < Math.min(x.length, y.length); i++) { 
     var xc = x[i]; 
     var yc = y[i]; 
     if (xc == yc) 
      continue; 
     var xclow = xc.toLowerCase(); 
     var yclow = yc.toLowerCase(); 
     if (xclow == yclow) 
      return xc < yc ? -1 : 1 
     else 
      return xclow < yclow ? -1 : 1; 
     return x.length.localeCompare(y.length); 
    } 
} 

順便說一句,最後的return語句是不必要的,因爲if和else都包含return語句。

還有更簡單的方法可以做到這一點,但我認爲你試圖自己完成。

+0

謝謝,但仍然返回值仍然不正確 – styx

+0

@styx:'compare(「Kka」,「kk」)'現在可以得到'-1'。怎麼了? – Bergi

+0

@Bergi,由於某種原因,我沒有工作,現在工作正常,謝謝 – styx

3

爲什麼不使用"Kk" === "kk"

function compare(x, y) { 
    return x === y; 
    // or return x === y ? 1 : -1 
} 
+1

你的答案是正確的,不知道誰downvoted你 –

+0

OP似乎並不想測試平等,而是寫一個[比較函數](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description) – Bergi