2016-11-07 44 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,請相應標記問題。 – 2016-11-09 05:29:20

回答

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'); 
    } 
} 

如果未找到該值,查找將返回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 
}