0

in for loops, array.splice doesn't work the array doesn't change

I changed some position, confirm it doesn't work in chrome.

var menu =['#men','#wmen','#ftwear','#accsries','#chldren','#dscver']

for( var i = 0; i < menu.length; i++){ 
 $(menu[i]).click(function(){
   menu.splice(i, 1);
   console.log(menu) 
   menu.forEach(function(list){
     $(list+' ul').slideUp(300)
     $(list).removeClass('bold') 
   })
   menu.splice(i, 0, menu[i]);
  console.log(menu) 
 })
 }

I hope the for Loops work with array.splice

Siu
  • 49
  • 7
  • Idk why Barmar marked this as a duplicate when the referenced post (while related) does not qualify as an answer for this post. To help you out @Siu keep in mind that the `$(elem).click()` method only registers a listener to your button. By the time the user clicks that button the `i` variable in your for loop will always be 6 (the length of your array). Thus the last element will always be spliced off. – Michael Sorensen May 23 '19 at 23:52

1 Answers1

0

You need to bind the value of i to the function inside the click - since it is called asynchronously. Try using let instead of var inside the for statement:

var menu =['#men','#wmen','#ftwear','#accsries','#chldren','#dscver']

for( let i = 0; i < menu.length; i++){ 
 $(menu[i]).click(function(){
   menu.splice(i, 1);
   console.log(menu) 
   menu.forEach(function(list){
     $(list+' ul').slideUp(300)
     $(list).removeClass('bold') 
   })
   menu.splice(i, 0, menu[i]);
  console.log(menu) 
 })
 }
Amit
  • 1,620
  • 1
  • 15
  • 24