0

Using jQuery, I am trying to check if a value x exists in my array. Basically, when clicking the testButton I have a var x that starts from zero Using this value I am trying to check if in the array there is an element with value 0. If there is, increment x and perform the array scan again. This should happen until x has a value which is not found in the array. Then at this point I know that I can use this id for the element. At the moment I have this code that checks if value x is in array, but this happens only for the length of the array. Next iteration should be: x=3, x is not in array so can be used as id. Can someone help to implement this. Thanks

  var array = ["0","1","2"];
  var x = 0;

  $("#testButton").click(function(){
        $.each(array, function(index,value){
            if($.inArray(x.toString(),array == -1)){
              console.log('found item with x value in array, increment x and scan the array again');
            }
            else{
              console.log('not in array, add id to element and push current x value to array.');
            }
            x=x+1;
        });
      });
3
  • 1
    work use of inArray should be if($.inArray(x.toString(),array) >= 0){ Commented Dec 12, 2016 at 23:05
  • Note use care with the ["0","1","2"]; vs a possible use of [0,1,2]; Commented Dec 12, 2016 at 23:09
  • Thanks. A bit off topic, how to check for [0,1,2]. In array performs check on strings. Commented Dec 12, 2016 at 23:19

2 Answers 2

1
var a = ["0","1","2"];
a.includes("2"); // true 
a.includes("4"); // false

copied from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Sign up to request clarification or add additional context in comments.

Comments

0
var array = ["0","1","2"];
var x = 0;

$("#testButton").click(function(){
  while(array.includes(x.toString())) x++;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.