Reputation: 693
Say I have a function that needs to check for a match with one of two different values. However, the input is very complicated:
function checker(id, value){
if (this.state.users[id].items[value].name === 'onething ' ||
this.state.users[id].items[value].name === 'theotherthing ' ){
// my action
}
}
What I end up doing is this:
function checker(id, value){
var name = this.state.users[id].items[value].name
if (name === 'onething ' || name === 'theotherthing '){
// my action
}
}
Is there any way to do something like this:
function checker(id, value){
if (this.state.users[id].items[value].name === 'onething ' || 'theotherthing '){
// my action
}
}
Obviously the second method takes less typing and is easier to refactor than the first one. How do they compare memory/speed wise?
Upvotes: 0
Views: 125
Reputation: 3423
In ECMAScript 2016 you can do something like:
if (['onething ','theotherthing'].includes(this.state.users[id].items[value].name)) {
//do stuff
}
The statement is composed of the following parts:
the if statement (obviously)
an array definition: ['onething ','theotherthing']
calling the method includes()
on the previously defined array.
In javascript an array is an object that has methods like any other object. One of those methods is includes()
which checks that the argument is contained inside the array. The return type of this method is boolean so it's directly evaluated by the if statement without any casting
More about includes()
method here
Upvotes: 2
Reputation: 386726
You could use Array#indexOf
and test against -1
if (['onething ', 'theotherthing '].indexOf(this.state.users[id].items[value].name ) !== -1){
Upvotes: 3
Reputation: 350766
You could use object notation:
if (this.state.users[id].items in {"onething ":1, "theotherthing ":1}){
Or, a regular expression could also work -- shorter, but less efficient:
if (/onething |theotherthing /.test(this.state.users[id].items)){
Upvotes: 0