最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - is there an equivalent of the ruby any method in javascript? - Stack Overflow

programmeradmin1浏览0评论

Is there an equivalent of ruby's any method for arrays but in javascript? I'm looking for something like this:

arr = ['foo','bar','fizz', 'buzz']
arr.any? { |w| w.include? 'z' } #=> true

I can get a similar effect with javascript's forEach method but it requires iterating through the entire array rather than short-circuiting when a matching value is found the way ruby's any method does.

var arr = ['foo','bar','fizz', 'buzz'];
var match = false;
arr.forEach(function(w) {
  if (w.includes('z') {
    match = true;
  }
});
match; //=> true

If I really wanted to short-circuit, I could use a for loop, but it's really ugly. Both solutions are super verbose.

var arr = ['foo','bar','fizz', 'buzz'];
var match = false;
for (var i = 0; i < arr.length; i++) {
  if (arr[i].includes('z')) {
    match = true;
    i = arr.length;
  }  
}
match; //=> true

Any thoughts?

Is there an equivalent of ruby's any method for arrays but in javascript? I'm looking for something like this:

arr = ['foo','bar','fizz', 'buzz']
arr.any? { |w| w.include? 'z' } #=> true

I can get a similar effect with javascript's forEach method but it requires iterating through the entire array rather than short-circuiting when a matching value is found the way ruby's any method does.

var arr = ['foo','bar','fizz', 'buzz'];
var match = false;
arr.forEach(function(w) {
  if (w.includes('z') {
    match = true;
  }
});
match; //=> true

If I really wanted to short-circuit, I could use a for loop, but it's really ugly. Both solutions are super verbose.

var arr = ['foo','bar','fizz', 'buzz'];
var match = false;
for (var i = 0; i < arr.length; i++) {
  if (arr[i].includes('z')) {
    match = true;
    i = arr.length;
  }  
}
match; //=> true

Any thoughts?

Share Improve this question asked Jun 23, 2015 at 1:40 williamcodeswilliamcodes 7,2869 gold badges37 silver badges59 bronze badges 2
  • developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Sean Hill Commented Jun 23, 2015 at 1:44
  • Array.prototype.some. Just had to put in a reference to ECMA–262 ed6 now that it's the specification. :-) – RobG Commented Jun 23, 2015 at 1:54
Add a ment  | 

2 Answers 2

Reset to default 9

You are looking for the Array.prototype.some method:

var match = arr.some(function(w) {
   return w.indexOf('z') > -1;
});

In ES6:

const match = arr.some(w => w.indexOf('z') > -1);
arr.filter( function(w) { return w.contains('z') }).length > 0
发布评论

评论列表(0)

  1. 暂无评论