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

javascript - Logical && of an array of strings - Stack Overflow

programmeradmin2浏览0评论

I'm trying to take a JavaScript array of strings, and return a boolean value based on all the elements in it. A logical && between non-empty strings should return true. I've found simple way to return a bool between two strings, using !!("String1" && "String2").

However, if I had these two strings in an array like var myArr = ["String1","String2"], how would I go about doing this?

I'm trying to take a JavaScript array of strings, and return a boolean value based on all the elements in it. A logical && between non-empty strings should return true. I've found simple way to return a bool between two strings, using !!("String1" && "String2").

However, if I had these two strings in an array like var myArr = ["String1","String2"], how would I go about doing this?

Share Improve this question asked Mar 29, 2015 at 23:57 AndrewAndrew 1,0402 gold badges19 silver badges34 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You're looking for the array every method bined with a Boolean cast:

var myArr = ["String1","String2"]
myArr.every(Boolean) // true

In fact you could use an identify function, or String as well, though to properly convey your intention better make it explicit:

myArr.every(function(str) { return str.length > 0; }) // true

Here's a nice solution using every:

function isEmpty(strings){
    return !strings.every(function(str){
        return !!str;
    });
}

Demo on JSFiddle

How about something like this?

function checkArr(arr) {
  for (var i = 0, length = arr.length; i < length; i++) {
    if (!arr[i]) return false;
  }
  return true;
}

checkArr(['a','b']); // true
checkArr(['a','']); // false

Or you could do it in a slightly hackish one liner:

return !arr.join(',').match(/(^$|^,|,,|,$)/);
发布评论

评论列表(0)

  1. 暂无评论