简体   繁体   中英

lodash .each and .trim ignoring array elements?

I'm trying to put together some demo lodash functionality and I'm running into some weird behavior.

I have an array of cars, plus some other non-string elements thrown in. I want to take each element of the array and remove it from the cars array, check if it's a string, if yes, trim off any trailing white space, add an 's' and push it into the pluralCars array.

I'm doing this in an angular controller and printing out the arrays in a view.

vm.cars = ['Saab ', 'Volvo', 'BMW ', 'Ford', 'Chevrolet ', 'Toyota', 'Honda', 'BMW', 45, true, false, null];
vm.pluralCars = [];

lodash.each(vm.cars, function(car) {
  if (lodash.isString(car)) {
    lodash.pull(vm.cars, car);
    lodash.trim(car);
    car = car + 's';
    vm.pluralCars.push(car);
  }
 });

The output of {{cars}} is:

["Volvo","Ford","Toyota","BMW",45,true,false,null]

And the output of `{{pluralCars}}' is:

["Saab s","BMW s","Chevrolet s","Hondas"]

Notice that Volvo, Ford, Toyota and BMW (w/o the trailing white space) were not pulled from the cars array, pluralized, and added to the pluralCars array.

And then the strings that were pulled did not have their white space trimmed.

Strings are immutable, they cannot be altered.

_.trim does return a new string, but you're just throwing away that result. You'll need to use

car = lodash.trim(car);

And apart from that it looks like you should simplify your code to

vm.pluralCars = lodash.map(lodash.filter(vm.cars, lodash.isString), function(car) {
  return lodash.trim(car) + 's';
});

without any _.pull ing - you don't want to modify vm.cars , and you certainly don't want to remove items while iterating it, as that will lead to skipping some. If you are looking for the array of non-string values as well, you can use _.partition instead of the filter.

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