what is Array.any? for javascript

I'm looking for a method for javascript returns true or false when it's empty.. something like Ruby any? or empty?

[].any? #=> false
[].empty? #=> true

Javascript standard library is quite poor compared to ruby's Enumerable, most stuff should be written by hand. On the bright side, this is trivial in most cases.

 Array.prototype.isEmpty = function() {
     return !this.length;
 }

 Array.prototype.any = function(func) {
    return this.some(func || function(x) { return x });
 }

Libraries like underscore already provide wrappers like these, if you're used to ruby's collection methods, it makes sense to include them in your project.

As @Pointy pointed out, JS arrays are not lists, they are just objects with numeric keys and length defined as max(keys) + 1 . Therefore true collection methods can give surprising results (like pretty much everything else in this language).


JavaScript native .some()方法完全符合您的需求:

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 arrays can be "empty", in a sense, even if the length of the array is non-zero. For example:

var empty = new Array(10);
var howMany = empty.reduce(function(count, e) { return count + 1; }, 0);

The variable "howMany" will be set to 0 , even though the array was initialized to have a length of 10 .

Thus because many of the Array iteration functions only pay attention to elements of the array that have actually been assigned values, you can use something like this call to .some() to see if an array has anything actually in it:

var hasSome = empty.some(function(e) { return true; });

The callback passed to .some() will return true whenever it's called, so if the iteration mechanism finds an element of the array that's worthy of inspection, the result will be true .

链接地址: http://www.djcxy.com/p/37754.html

上一篇: 递归地从JavaScript对象中删除空值

下一篇: 什么是Array.any? 为JavaScript