2016-11-07 42 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 
}