I have an array of Objects in JavaScript and I'm having trouble accessing JS methods on my array.
Is there a way to use methods such as removeClass
or attr
on an array without having to use a for loop? For example, in jQuery if I do $("li.listing").removeClass("listing")
....it will remove the listing
class from all li
tags where this class is present.
Is there a way without having to use multiple for loops, to use these methods on an array (so that it looks at each element/object in the array)?
Example
cars.removeClass("listing")
// Remove listing
class from every element in cars array - is this syntax or something similar possible? Thanks!
Array index [0] example
0: m.fn.init [
li#listing-MCMR-R-ZT-BFNT001-ZT-BFNT001.listing.filtered-out-by-car-type.listing-filtered-out,
prevObject: m.fn.init(1),
context: car,
selector: "li.listing"
]
答案 0 :(得分:2)
You can use Array.prototype.map to simplify the syntax a bit, but it is essentially also going to loop through all the elements. Under the hood, jQuery is also looping through them, all it is doing is giving you a nice way to access that without having to write the loop yourself
for your example:
cars.map(function(car) {
return car.removeClass('listing');
});
As pointed out in the comments, Array.prototype.forEach Is probably preferable if you're only looking to mutate or apply the function on the current array and not return anything new. In either case, this is the most succinct way of going through an array without using an explicit for loop