简体   繁体   中英

Can not delete an element of array in JavaScript

I have a part of code in which the function removeClass must delete an element of array in case, if some of his elements coincides with input parameters.

But it does not work.

 var obj = { className: 'open menu' }; function removeClass(obj, cls) { var arr = obj.className.split(' '); for (var i = 0; i < arr.Length; i++) { if (cls == arr[i]) delete arr[i] } obj.className = arr.join(' '); return obj.className; } console.log(removeClass(obj, 'open')); // desired output obj.className='menu' // actual output 'open menu' 

You can use Array.prototype.filter() method for this.

var obj = {
  className: 'open menu'
};

function removeClass(obj, cls) {
  var arr = obj.className.split(' ');

  obj.className = arr.filter(function(item) {
    return cls !== item;
  }).join(' ')

  return obj.className;
}

console.log(removeClass(obj, 'open'));

In your code, you have used arr.Length . Actual syntax is arr.length . But even if you use fix your code then, it will not delete the item instead put undefined on its place, then you have to handle extra white spaces. That's why I think above solution is good.

Try this:

  var obj = { className: 'open menu dogs cats' }; function removeClass(obj, cls) { return (obj.className = obj.className.split(' ').filter(item => cls !== item).join(' ')); } console.log(removeClass(obj, 'open')); console.log(removeClass(obj, 'dogs')); 

But if you are trying to do this to a DOM element then use classList instead.

 var el = document.getElementById("mine"); console.log(el.className); el.classList.remove('open'); console.log(el.className); el.classList.remove('dogs'); console.log(el.className); 
 <div id="mine" class="menu open dogs cats"></div> 

Why just don't replace the string?

 var obj = { className: 'open menu' }; function removeClass(obj, cls) { return obj.className = obj.className.replace(cls, '').trim() } console.log(removeClass(obj, 'open')); // obj.className='menu' 

Also while working with DOM there are already methods for dooing this

 const b = document.querySelector('button') b.addEventListener('click', () => { b.classList.remove('blue') }) 
 .red { color: red } .blue { color: blue } 
 <button class="red blue">test</button> 

With ES6 you can even make this really short

function removeClass(element, classToRemove) {
    return element.className.split(' ')
                  .filter(class => class !== classToRemove)
                  .join(' ');
}

If you want to modify the element itself, just reassign the return value to element.className

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM