The any type allows us to assign literally “any” particular value to that variable, simulating what we know as plain JavaScript - where types can dynamically be assigned from different types, such as a String value becoming a Number.
Types Array<any> and any[] are identical and both refer to arrays with variable/dynamic size.
Any[] is for array of objects with type Any.
JavaScript Array some()The some() method checks if any array elements pass a test (provided as a callback function). The some() method executes the callback function once for each array element. The some() method returns true (and stops) if the function returns true for one of the array elements.
The JavaScript native .some()
method does exactly what you're looking for:
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
JavaScript has the Array.prototype.some()
method:
[1, 2, 3].some((num) => num % 2 === 0);
returns true
because there's (at least) one even number in the array.
In general, the Array
class in JavaScript's standard library is quite poor compared to Ruby's Enumerable. There's no isEmpty
method and .some()
requires that you pass in a function or you'll get an undefined is not a function
error. You can define your own .isEmpty()
as well as a .any()
that is closer to Ruby's like this:
Array.prototype.isEmpty = function() {
return this.length === 0;
}
Array.prototype.any = function(func) {
return this.some(func || function(x) { return x });
}
Libraries like underscore.js and lodash provide helper methods like these, if you're used to Ruby's collection methods, it might make sense to include them in your project.
I'm a little late to the party, but...
[].some(x => !!x)
var a = [];
a.length > 0
I would just check the length. You could potentially wrap it in a helper method if you like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With