2016-11-07 17 views
-1

値を配列に挿入する際に問題が発生しています。最初はうまくいきますが、すでに配列内にある要素を再度クリックすると、配列の最後に移動(プッシュ)します。これを修正する方法はありますか?ここで配列に既に挿入されている要素が再挿入されないようにする

は私のコードです:

function unique(list) { 
    var result = []; 

    $.each(list, function(i, e) { 
     var txt = $.trim(e); 

     if ($.inArray(txt, result) == -1) { 
      // pushing the element onto the end 
      // and returning it 
      // sorting is not the issue 
      result.push(e); 
     } else { 
      return; 
     } 
    }); 

    // sort 
    result.sort(); 

    return result.join(", "); 
} 

例は、私がa.phpをクリックし、b.phpということであり、それが正常に動作し、a.phpをb.php前にソートされているが、私は上をクリックした場合a.phpをもう一度押すと、b.phpが配列の先頭まで移動します。これをチェックする方法はありますか?

ありがとうございます!

+0

クリックを削除します最初の使用後のリスナー? – Teemu

+0

これがjQueryの場合は、それに応じてタグを付けてください。 –

答えて

0

私はこの質問よりも堅牢な回答があります。しかし、私はあなたがまっすぐな、まあまあでない答えを探していると思います(例えば、ES6にリエンジニアリングするつもりはなく、別のライブラリなどを紹介するつもりはありません)。

Array.prototype.findを使用できます。

var arr = [ 1, 2, 3 ]; 
function insertIfNoDupes (num) { 
    if (! arr.find (num)) { 
     arr.push (num); 
    } else { 
     console.log ('Value already exists in array'); 
    } 
} 

値が見つからない場合、Findはundefinedを返します。

0

要素にカスタム値を追加できます。たとえば、私は4つのボタン

<input id="btn1" type="button" value="Click me" onclick="addToArr(this)"><br/> 
<input id="btn2" type="button" value="Click me" onclick="addToArr(this)"><br/> 
<input id="btn3" type="button" value="Click me" onclick="addToArr(this)"><br/> 
<input id="btn4" type="button" value="Click me" onclick="addToArr(this)"><br/> 

と配列変数を持って

var arr []; 
値が定義されていない場合、私はちょうど要素にカスタム値を追加する必要が

function addToArr(elem){ 
    //If the element does not have 'addedToArr' defined, 
    //or the value of 'addedToArr' is not 'false' (which makes the condition true) 
    if (!elem.addedToArr){ 
     arr.push(elem.id); //Push the element's id into array 
     elem.addedToArr = true; //Set 'addedToArr' of the element to true 
    } 
    alert(arr.length); //This will alert the new length of the array 
} 
関連する問題