我想从可用ID列表中选择一个随机ID。选择后,我想检查是否有该ID的项目,如果没有,那么我想在那里添加。如果存在,那么我想再次生成ID,直到它选择不存在的ID。
问题:
当前,我正在使用if statement
检查是否存在ID,是否存在,然后再次生成。但是,问题是它仅检查一次。
可能还存在新选择的ID,因此我想继续检查,直到找到某些ID不存在为止。为此,我需要使用循环,但是我无法弄清楚如何做到这一点,因为这些项目是动态添加的。
这是我尝试过的:
html:
<input type="button" id="button" value="Add new" />
<ul class="items">
<li id="a4">item with id a4</li>
<li id="c2">item with id c2</li>
<li id="c3">item with id c3</li>
<li id="a1">item with id a1</li>
</ul>
JavaScript:
function randID () {
var arr = new Array("c1", "c2", "c3", "c4", "a1", "a2", "a3", "a4","a5","a6");
var index = Math.floor(Math.random()*(arr.length));
return arr[index];
}
$('#button').click(function() {
var newID = randID();
if ( $('.items').find('#'+newID).length > 0 ) {
var newID = randID();
}
$('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');
});
JSFIDDLE:https://jsfiddle.net/o4ul6gaj/
循环和检查是否取出ID是否创建性能瓶颈的整个想法。
我建议生成看似随机的ID,例如在JavaScript中创建GUID/UUID?
如果您确实需要从列表中获取ID,请在使用列表后从列表中删除ID。例如
var listOfIDs = ['id1', 'id2',.., 'idn'];
function getNewRandomId()
{
var n = Math.floor(Math.random()*(listOfIDs.length));
return listOfIDs.splice(n,1);
}
您想做的就是使用一个wir loop这样的循环:
$('#button').click(function() {
var newID = randID();
var found = $('.items').find('#'+newID).length > 0;
var trys = 0;
while (found && trys < 10){
newID = randID();
found = $('.items').find('#'+newID).length > 0;
trys++;
}
$('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');
});
但是,我建议在数据元素中跟踪使用的ID,并且仅从其余可能的ID中选择一个随机的ID。
var possibleIds = new Array("c1", "c2", "c3", "c4", "a1", "a2", "a3", "a4","a5","a6");
function randID () {
var index = Math.floor(Math.random()*(possibleIds.length));
return possibleIds[index];
}
$('#button').click(function() {
// check if there are any possible Ids
if(possibleIds.length > 0){
var newID = randID();
$('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');
// remove used Id from possibleIds
possibleIds = possibleIds.filter((id) => id !== newID);
}else{
console.log("no id left!");
}
});
我建议用while
替换if
,但是您需要额外的条件以确保一旦添加每个项目就不会无限。如果您已经有所有项目,也许return
在功能中的第一件事?
尝试使用
var newID = randID();
while ($('.items').find('#'+newID).length > 0 ) {
var newID = randID();
}
$('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');
只需使用长度检查ID即可。
if($('#myid').length==0)
{
//Create the Item
}
使用一段循环
function randID () {
var arr = new Array("c1", "c2", "c3", "c4", "a1", "a2", "a3", "a4","a5","a6");
var index = Math.floor(Math.random()*(arr.length));
return arr[index];
}
function createItem(){console.log("createItem");
var newID = randID();
console.log($('.items').find('#'+newID).length);
if ( $('.items').find('#'+newID).length > 0 ) {
console.log("generated again. Old id was " + newID);
return 0;
}
else{
return newID;
}
}
$('#button').click(function() {
var newID = 0;
while(newID==0){
newID = createItem();
}
$('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');
});