ı couldn't pop() every array list. at the end remain two array elements
function ürünSil(){
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"]
for(let i in diller){
let sonİcerik = diller.pop()
document.write(diller "<br />")
}
}
CodePudding user response:
you can empty your array like this also:
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"];
while(diller.length > 0) {
diller.pop();
}
console.log(diller)
CodePudding user response:
The length of the array changes each time on pop()
so when there are 3 items removed from the array , the present index for i
on your code will be 2
and hence the actual length is also 2, so the for()
loops does not trigger further.
The solution could be to preserve the initial length value and use that value in the loop:
function ürünSil(){
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"]
const length = diller.length;
for(let i = 0; i<length; i ){
let sonİcerik = diller.pop()
console.log(sonİcerik);
}
}
ürünSil()
CodePudding user response:
use while loop instead of for.
while (diller.length != 0) {
diller.pop();
document.write(diller '<br />');
}
CodePudding user response:
This happens because pop
reduces the length of the array, which impacts the times the loop will iterate. Instead just have the while
condition check whether the array still has elements, without any i
.
Unrelated, but
don't use
document.write
for this. Useconsole.log
, or if you want to add data to the HTML document, then use other DOM methods.have the good habit of ending your statements with semicolon. You don't want to fall for the sometimes tricky effects of automatic semicolon insertion.
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"];
while (diller.length) {
let sonİcerik = diller.pop();
console.log(sonİcerik);
}