2017-01-25 122 views
0

を使用してアレイ内にあるかどうかを確認:文字列は、私は、次のコードを持ってjQueryの

function checkIfUnitCostItemsAreZero(finaliseIDList) 
{ 
    var selectedItems = finaliseIDList; 
    selectedItems = $.makeArray(selectedItems); //array is ["-2,-3"] 
    var getItem = $("#builderItemsList .listItem"); 
     for (i = 0; i < getItem.length; i++) 
     { 
      var currentItem = ($(getItem[i]).attr("key")); 
      if (currentItem.indexOf(selectedItems) > -1) 
      {//currentItem = "-2" then "-3" 
       var unitCost = $(getItem[i]).attr("unitcost"); 
       console.log(unitCost); 
       unitCost = parseFloat(unitCost); 
       if(unitCost==0.00) 
       { 
        return true; 
        break; 
       } 
      } 
     } 
    return false; 
} 

選択された項目が現在、以下に等しい:

selectedItems = ["-2,-3"] 

ダウンまた、のCurrentItemがで評価されます。 "-2"、および次のループ"-3"

どちらの場合もどちらもifステートメントには入りません。なぜどんなアイデア?

+1

あなたの配列に間違いがあると思います。これは 'selectedItems = [" -2 "、" -3 "]'でなければなりません。 – Aer0

+0

あなたの戦略全体が正しくないと思うので、 'selectedItem'の' currentItem'を探すべきです。 –

+1

if条件をこれに変更して、結果を教えてください: 'selectedItems.indexOf(currentItem)> -1' –

答えて

0

HosseinとAer0の提供:以下を使用して固定 - 文字列は単一の値として渡されます。配列を分割するにはsplitを使用します。 - if節を変更します。

function checkIfUnitCostItemsAreZero(finaliseIDList) 
{ 
    var selectedItems = $.makeArray(finaliseIDList.split(',')); 
    var getItem = $("#builderItemsList .listItem"); 
     for (i = 0; i < getItem.length; i++) { 
      var currentItem = ($(getItem[i]).attr("key")); 
      if (selectedItems.indexOf(currentItem) > -1) 
       { 
        var unitCost = $(getItem[i]).attr("unitcost"); 
        unitCost = parseFloat(unitCost); 
        if(unitCost==0.00) 
         { 
         return true; 
         break; 
         } 
       } 
     } 
     return false; 
} 

PS解決策が動作するときは、なぜ投票してください:/あなたは、回答またはコメントで少なくともdownvote atleastをバックアップしますか?

関連する問題