I have a school assignment and I have an issue with deleting something from an array of indexes. This is what I currently have.
Function that returns array length:
function DolzinaPolja(polje){
return polje.length-1;
}
new constructor
function oseba(ime, priimek, stranka) {
this.ime=ime;
this.priimek=priimek;
this.stranka=stranka;
}
function that creates an object and pushes it into an array
function UstvariObjekt(ime,priimek, stranka) {
if (ime.length == 0 || priimek.length == 0 || stranka.length == 0) {
throw "Parametri niso popolni!";
}
else {
var novaoseba=new oseba(ime, priimek, stranka);
polje.push(novaoseba);
console.log(novaoseba.ime, novaoseba.priimek, novaoseba.stranka);
}
}
function that deletes an object from the array
function OdstraniIzPolja(x) {
if(x > polje.length - 1 || x == polje.length) {
throw"Polje ni tako veliko!";
}
for(var i=0; i<=polje.length-1;i++) {
if(x==polje[i]) {
polje.splice(x,1);
return true;
}
return false;
}
}
I am having an issue with deleting an object from the array. Here are my tests.
var polje = [];
var x=0;
UstvariObjekt("Rene","Vucko","Stranka");
UstvariObjekt("R","V","S");
UstvariObjekt("X","Y","Z");
OdstraniIzPolja(x);
console.log(polje[0]);
console.log(polje[1]);
console.log(polje[2]);
console.log(DolzinaPolja(polje));
SO my array should be the length of 2. Since I start with 0,1,2. What I don't understand is why doesn't my function that deletes an object from the array delete the object? I've played around a little bit but often it just deletes the wrong object.
Also is the if clause for x if the length is smaller than the array length written ok?
---UPDATE---- IF I write polje.slice(2,1) without the function just in the program, it deletes the right one. So obviously something is wrong with the loop. This is my updated code.
function DolzinaPolja(polje){
return polje.length-=1;
}
function OdstraniIzPolja(x)
{
if(x>polje.length-1 || x==polje.length)
{
throw"Polje ni tako veliko!";
}
for(var i=polje.length-1;i>=0;i--)
{
if(x==polje[i]){
polje.splice(i,1);
return true;
}
return false;
}
}
--EDIT-- here's the code https://jsfiddle.net/2y07wtkL/
OdstraniIzPoljafunction, sincexis an index and you're checking to see if it's in the proper range... you shouldn't need the loop at all, right?