Type Conversion with JavaScript Arrays

Publikováno: 7.5.2019

JavaScript’s loose nature allows developers to employ amazing tricks to do just about anything you’d like. I’ve detailed how you can filter falsy values in arrays using a filter(Boolean) trick, but reader David Hibshman shared another trick for typecasting array values the same way. To typecast an array of elements, you can use map and […]

The post Type Conversion with JavaScript Arrays appeared first on David Walsh Blog.

Celý článek

JavaScript’s loose nature allows developers to employ amazing tricks to do just about anything you’d like. I’ve detailed how you can filter falsy values in arrays using a filter(Boolean) trick, but reader David Hibshman shared another trick for typecasting array values the same way.

To typecast an array of elements, you can use map and the desired return type:

["1", "9", "-9", "0.003", "yes"].map(Number);
// ["1", "9", "-9", "0.003", "yes"].map(Number);

I love this trick but you could argue the code itself could be considered confusing, so wrapping it a helper function would be helpful:

function arrToNumber(arr) {
  return arr.map(Number).filter(Boolean);
}

Validation could and should probably be more rigorous but basic validation through typecasting might help you!

The post Type Conversion with JavaScript Arrays appeared first on David Walsh Blog.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace