-2

I'm super new to javascript and learning.

I have this piece of code and it is running and getting the job done.

(this.name == ('nodepy') || this.name == ("nonlinear-waves-course") || this.name == ("SSP_Tools"))

but now I want to define an array or list of strings

var listOfRepos = ["nodepy", "nonlinear-waves-course", "SSP_Tools"];

How do I go about checking if "this.name" is in "listOfRepos"?

In python, I can just write something like this:

this.name in listOfRepos

Again, I'm new to javascript. Very little experience. Thank you so much in advance.

kirikoumath
  • 673
  • 6
  • 14

1 Answers1

2

Use indexOf()

if (~listOfRepos.indexOf(this.name)){
    alert('true');
}

Explanation:

indexOf() returns the value's index in your array if it is in the array, if it's not it will return -1. I'm using the bitwise not operator ~

Bitwise NOT inverts the bits of its operand.

Above could also be written as

if (listOfRepos.indexOf(this.name) > -1) {}
baao
  • 62,535
  • 14
  • 113
  • 168
  • Bad idea to promote the use of the confusing `~` operator. –  Aug 29 '15 at 06:26
  • @torazaburo Have a look [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT), maybe that makes it clearer for you – baao Aug 29 '15 at 06:41
  • I know exactly what it does. The problem is that 80% of JS programmers looking at the code will not. That's why it's generally discouraged. As this accepted answer with 37 upvotes says, *It's also a (generally) unclear trick*. http://stackoverflow.com/questions/12299665/what-does-a-tilde-do-when-it-precedes-an-expression –  Aug 29 '15 at 07:38