var thelist = new Array();
function addlist(){
thelist.push(documentgetElementById('data').innerHTML);
}
How can I check that the data I push does not already exsist in array thelist
?
Answer
var thelist = []; // Use the array literal, not the constructor.
function addlist(){
// get the data we want to make sure is unique
var data = documentgetElementById('data').innerHTML;
// make a flag to keep track of whether or not it exists.
var exists = false;
// Loop through the array
for (var i = 0; i < thelist.length; i++) {
// if we found the data in there already, flip the flag
if (thelist[i] === data) {
exists = true;
// stop looping, once we have found something, no reason to loop more.
break;
}
}
// If the data doesn't exist yet, push it on there.
if (!exists) {
thelist.push(data);
}
}
No comments:
Post a Comment