Javascript 防止重新插入已插入数组的元素
我遇到了将值推入数组的问题。它一开始工作正常,但是如果我重新单击数组中已经存在的元素,它会将其移动(推送)到数组的末尾。有办法解决这个问题吗 这是我的密码:Javascript 防止重新插入已插入数组的元素,javascript,arrays,Javascript,Arrays,我遇到了将值推入数组的问题。它一开始工作正常,但是如果我重新单击数组中已经存在的元素,它会将其移动(推送)到数组的末尾。有办法解决这个问题吗 这是我的密码: function unique(list) { var result = []; $.each(list, function(i, e) { var txt = $.trim(e); if ($.inArray(txt, result) == -1) { // pu
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将上移到数组的前面。有没有办法检查这样就不会发生
谢谢 这个问题有比我要给出的答案更有力的答案。但我认为您正在寻找一个直截了当、或多或少幼稚的答案(例如,您不打算重新设计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' );
}
}
如果找不到值,“查找”将返回“未定义”。您可以向元素添加自定义值。例如,我有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/>
如果没有定义值,我只需要向元素添加一个自定义值
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
}
第一次使用后删除click listener?如果这是jQuery,请相应地标记问题。
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
}