Avoiding a priori a priori using JavaScript

For example, I have this code:

var Foo = [1,2,3,4];

function searchInFoo(n) {
    for(var i = 0, arrayLength = Foo.length; i < arrayLength; i++) {
        if(Foo[i] === n) {
            console.log("N: " + n + " found!");
        } else {
            console.log("N: " + n + " not found!");
        }
    }
}


searchInFoo(4);

Well, as I expected, an Foo array with n elements, I also have iterations of the for loop. It's great. Thus, if I call the searchInFoo function with any n parameter, my function will also execute all blocks in the if else statement n times. For example, in the above example, I once registered "n found" and three times "N: n not found!".

What is the best approach to avoid executing the else block without losing some of the basic error trap functions, which actually happens when I omit the block of whole blocks, like here:

var Foo = [1,2,3,4];

function searchInFoo(n) {
    for(var i = 0, arrayLength = Foo.length; i < arrayLength; i++) {
        if(Foo[i] === n) {
            console.log("N: " + n + " found!");
        } 
    }
}


searchInFoo(1);
+4
source share
1 answer

In this case, the loop is not needed:

var foo = [1,2,3,4];

function searchInFoo(n) {
    if(foo.indexOf(n) > -1) {
        console.log("N: " + n + " found!");
    } 
}
searchInFoo(1);

. , .

, :

function searchInFoo(n) {
    return foo.indexOf(n) > -1;
}
console.log(searchInFoo(1) ? 'found' : 'not found');

, , , forEach map (, MDN). , ?

function myforeach(arr, fn) {
    for(var i=0; i<arr.length; i++) {
        fn(arr[i]);
    }
}
myforeach([1,2,3], function(el) {
    console.log(el === 1);
}); // logs true, false, false

map :

function mymap(arr, fn) {
    var retArray = [];
    for(var i=0; i<arr.length; i++) {
        retArr.push(fn(arr[i]));
    }
    return retArray;
}
var validated = myforeach([1,2,3], function(el) {
    return el === 1;
}); // returns [true, false, false]
+4

All Articles