2

I have a question whether this is possible or not.
For example, there is one code like below. But that code has an error for sure.
And I want to make if is true when one data is at some array.
Could you recommend some method?

This is my code:

var a = 1;
var model2 = [1, 2, 3];
if (a == model2) {
    var b = a;
} else {
    var c = a;
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
DD DD
  • 1,148
  • 1
  • 10
  • 33
  • 1
    `{1, 2, 3}` is neither an array nor an object, it's causes a syntax error in this case. What is `model2` supposed to be? An array? – ibrahim mahrir Dec 13 '18 at 23:26
  • First, is `model2` supposed to be `[1, 2, 3]`? If so, are you trying to find an item in the array? – Darlesson Dec 13 '18 at 23:29
  • You can try to use a dictionary. This might help: [Checking if a key exists in a JavaScript object?](https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object) – mdelapena Dec 13 '18 at 23:30
  • Yes. I am sorry. I made a mistake and changed that for making an arryay. – DD DD Dec 13 '18 at 23:54

3 Answers3

3

Based on the structure, I believe that model2 is meant to be an array. Arrays are created with the [] square brackets rather than the {} curly braces, which are used for code blocks and objects. model2 should look like this:

var model2 = [1, 2, 3];

As for checking whether something is within an array, you would use Array.prototype.includes():

if (model2.includes(a)) {...}

What .includes() does is check, does the array (model2) include the passed variable/value (a), and returns a Boolean value (true or false) depending on whether the value actually is in the array.

Full working code:

var a = 1;
var model2 = [1, 2, 3];
if (model2.includes(a)) {
    var b = a;
}
else {
    var c = a;
}

Further reading:

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
2

you're not creating an array with var model2 = {1, 2, 3}, you should define as

var model2 = [1,2,3]

Case you wanna use arrays. then you can just use the include method

if(model2.includes(a)){
  var b = a
}else{
  var c = a
}

It should help!

1

Firstly this isn't an array but an object and a broken one to boot. Arrays are defined with [ ] brackets.

Now to your question. Arrays have a prototype function called .includes()

Read up on it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Mind you, this isn't supported by IE11 so if this is a priority to you let me know and I'll update this answer.

Nnay
  • 132
  • 6
  • 1
    _"... you will most likely have to resort to looping through each item of the array"_. That's not the only way, OP could use the widely supported `indexOf` and check if the return value is not `-1`: `.indexOf(a) !== -1`. – ibrahim mahrir Dec 14 '18 at 00:04