I'm trying to find a better way to do this in Javascript:
if ( text === 'amy' ) {
var url = 'http://www.mydomain.com/amylikescats.html';
}
else if ( text === 'dave' ) {
var url = 'http://www.mydomain.com/daveshome.html';
}
else if ( text === 'steve' ) {
var url = 'http://www.mydomain.com/steve2.html';
}
else if ( text === 'jake' ) {
var url = 'http://www.mydomain.com/jakeeatstofu.html';
}
else {
var url = 'http://www.mydomain.com/noone.html';
}
Is there a more code efficient way of doing this?'
Use an object as a map:
var map = {
"amy": 'http://www.mydomain.com/amylikescats.html',
"dave": 'http://www.mydomain.com/daveshome.html',
// etc
};
var text = "whatever";
var url = map[text] === undefined ? 'http://www.mydomain.com/noone.html' : map[text];
This will save you the maximum amount of repeated code, but if you also need to do other stuff than setting url a switch might be more appropriate.
Switch statement!
var url = 'http://www.mydomain.com/noone.html';
switch(text) {
case 'amy': url = 'http://www.mydomain.com/amylikescats.html';
break;
case 'dave': url = 'http://www.mydomain.com/daveshome.html';
break;
case 'steve': url = 'http://www.mydomain.com/steve2.html';
break;
case 'jake': url = 'http://www.mydomain.com/jakeeatstofu.html';
break;
}
Now there is no need for a default clause because you've initialized url before the switch.
Otherwise you could add this:
default: url = 'http://www.mydomain.com/noone.html';
break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With