Check if all elements of an array are strings

Is there a good way to check if all indices in an array are strings?

check(["asd", 123]); // false
check(["asd", "dsa", "qwe"]); // true

      

+3


source to share


4 answers


You can use Array.every

to check if all elements are strings.



function check(x) {
    return x.every(function(i){ return typeof i === "string" });
}

      

+9


source


You can do something like this - iterate over the array and check if it's all a string or not.



function check(arr) {
 for(var i=0; i<arr.length; i++){
   if(typeof arr[i] != "string") {
      return false;
    }
 }

 return true;
}

      

+2


source


Something like that?

var data = ["asd", 123];

function isAllString(data) {
    var stringCount;
    for (var i = 0; i <= data.length; i++) {
        if (typeof data[i] === 'string')
            stringCount++;
    }
    return (stringCount == data.length);
}

if (isAllString(data)) {
    alert('all string');
} else {
    alert('check failed');
}

      

0


source


My way:

check=function(a){
    for ( var i=0; i< a.length; i++ ) {
        if (typeof a[i] != "string")
            return false;
    };
    return true;
}
console.log(check(["asd","123"])); // returns true
console.log(check(["asd",123])); // returns false

      

0


source







All Articles