Praveen
Praveen

Reputation: 56501

Iterating an array

I have framed an array like below

iArray = [true, true, false, false, false, false, false, false, true, true, true, false, 
true, false, false, false, false, true] 

Condtional check: If anyone of the value in this array is false I will be showing an error message else if everything is true I will be showing success message.

I tired below code to iterate, however couldn't frame the logic in it.

var boolIteration = iArray.split(',');
var i;
for (i = 0; i < boolIteration.length; ++i) {
    //conditional check
}

I'm struggling to iterate the array using the above condition.

Can anyone point me in the right direction with an efficient solution.

Upvotes: 1

Views: 83

Answers (5)

KooiInc
KooiInc

Reputation: 122908

Aternatives:

if (/false/i.test(iArray)) { }

or

if ( ''.replace.call(iArray,/true|,/g,'').length ) { }

Upvotes: 1

Oleg
Oleg

Reputation: 9359

No need for jQuery

if (iArray.indexOf(false) !== -1) {
    // error
}

Also, as previous commenters have already pointed out, iArray is already an array, there's no need to use split on it.

The Array.prototype.indexOf is not available in Internet Explorer below 9. However, this functionality could be easily added with a matching algorithm. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf for compatibility and how to create a workaround.

Upvotes: 4

Brandon Montgomery
Brandon Montgomery

Reputation: 6986

The jQuery.inArray function is nice for checking to see if a particular value is contained within an array.

iArray = [true, true, false, false, false, false, false, false, true, true, true, false, true, false, false, false, false, true];
if ($.inArray(iArray, false) >= 0) {
  // the value "false" is contained within the array, show an error message
}

Upvotes: 0

Alexander Perechnev
Alexander Perechnev

Reputation: 2837

 var iArray = [true, true, false, false, false, false, false, false, true, true, 
true, false,true, false, false, false, false, true];

    for (var i = 0; i < iArray.length; i++) {
        if (iArray[i]) {
            alert("success");
        }
        else {
            alert("error");
        }
    }

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

iArray is already an array, so there is no need to split it again (split is a method for String, Arrays don't have it)

What you need to do is check the index of a false value, if it is there then there is a false value in the array.

using jQuery - the array indexOf is not used because of IE compatibility

iArray = [true, true, false, false, false, false, false, false, true, true, true, false, 
true, false, false, false, false, true] 
if($.inArray(false, iArray ) != -1){
    //error
}

Upvotes: 2

Related Questions