Checking For An Empty String Array
Solution 1:
Beside the proposed using of Array#toString
method, I suggest to use Array#join
with an empty string as separator and then test the result. The advantage is, it works for an arbitrary count of elements inside of the array.
varbool = array.join('') ? 'not all empty string' : 'all empty string';
Solution 2:
['', ''] == ['', '']
returns false
because in JavaScript arrays are objects, and objects in JavaScript have reference semantics. Comparing objects to each other actually compares their reference IDs, which will be different for different references. So, even though both sides of ==
are the "same" array, they are different references.
If you want to check that an array only contains empty strings, use Array.prototype.every
as in the following:
myArray = ['']
console.log(myArray.every(el => el === '')) // true
myArray = []
console.log(myArray.every(el => el === '')) // true
myArray = ['test']
console.log(myArray.every(el => el === '')) // false
If you are in an environment without ES6 support, you can swap the el => el === ''
for function(el) { return el === '' }
.
Solution 3:
You can do this:
var arr = ["","", ""].reduce(function (a, b) {
return a + b;
});
if(arr == "") {
console.log('Array is empty');
}
Solution 4:
This should also work:
var arr = [""];
console.log(String.valueOf(arr[0]) === String.valueOf(''));
Solution 5:
Based on the answer from Nina above this should also work!
let arr1 = ['']
const bool1 = !!arr1.join(''); // falseconsole.log(bool1)
let arr2 = ['String']
const bool2 = !!arr2.join(''); // trueconsole.log(bool2)
Post a Comment for "Checking For An Empty String Array"