I have a js array like that:
let data = [{status:"stay",points:[1,2,3,4,5]}, {status:"move",points:[1,2,3,4,5]},{status:"stay",points:[1,2,3,4,5]}]
And I want to do some pattern match, here is my code:
switch (data){
case [{status:"move",_},{status:"stay",_},{status:"move",_}]:
console.log("successfully!")
}
And I don't care the points array, but in js the placeholder "_" not exist, actually I know other method to do this, but if we just use switch-case, can it be solved?
I am a newbie of js, anynoe knows how to do it?
If I understand what you're trying to do correctly, you might try reducing your array to a string, and then use that string in the switch statement. Something like this:
var actionString = ""
data.forEach(function(datum) {
actionString += datum.status + ' ';
});
// Remove extra space at the end
actionString.trim();
console.log(actionString); // "move stay move"
Then your switch statement would be:
switch(actionString) {
case "move stay move":
console.log('success!');
break;
case "stay move stay":
console.log('failure?');
break;
/* etc */
}
Try
switch (data.status){
case "stay":
case "move":
console.log("successfully!")
break;
}
Documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Related
I wish to use case within a switch switch statement like so:
case 'transfer' + amount:
sql.get(`SELECT * FROM scores WHERE userId ="${userID}"`).then(row => {
sql.run(`UPDATE scores SET points = ${row.points - amount} WHERE userId = ${userID}`);
bot.sendMessage({
to:channelID,
message: `You have transferred ` + amount + ` points. You currently have ${row.points} points.`
})
break;
If it sees transfer10 I want the code to take that value 10 to be amount however I have no idea how to do that.
Thanks in advance :)
I do not think you can create switch statement with dynamic-generated case statements. I also do not see any real advantage of doing this, plus the logic behind this it would be hard to understand from anyone else who will be reading the code.
What about using the switch statement do determine the art of action and accessing the _amount_in the case statements ?
var amount, action;
// some code
...
amount = 2;
// some code
...
action = 'transfer' // or delete, update ...
// some code
...
switch(action) {
case 'transfer':
// do some SQL and access the amount
...
break;
case 'delete':
// do some SQL and access the amount
break;
default:
// some default action
}
If you really need something like a dynamically-created switch-statement look at the first answer from this question.
Not sure why the code below is not working. It should take in a string and convert a G to a C and an A to a T and vice versa. However, it collects the input string but doesn't provide any output i.e. the alert just says "here is your reverse complement DNA"
var dnaSequence = prompt("Enter your DNA sequence here", "");
var newSequence = reverseComplement(dnaSequence);
alert("here is your reverse complemented DNA: " + newSequence);
function reverseComplement(dnaString) {
var reverseC = [];
var dnaArr = dnaString.split('');
for (var i = 0; i < dnaArr.length; i++) {
switch (dnaArr[i]) {
case 'A':
reverseC.push('T');
break;
case 'T':
reverseC.push('A');
break;
case 'C':
reverseC.push('G');
break;
case 'G':
reverseC.push('C');
break;
}
}
// Reverse and rejoin the the string
return reverseC.reverse().join('');
}
It should take in a string and convert a G to a C and an A to a T and vice versa.
Then you don't need the reverse(), because you are pushing in order.
Also, Make sure that you are entering uppercase letters into the prompt.
Else, you can force the uppercase.
This is the code with the two fixes:
function reverseComplement(dnaString) {
var reverseC = [];
var dnaArr = dnaString.toUpperCase().split('');
for (var i = 0; i < dnaArr.length; i++) {
switch (dnaArr[i]) {
case 'A':
reverseC.push('T');
break;
case 'T':
reverseC.push('A');
break;
case 'C':
reverseC.push('G');
break;
case 'G':
reverseC.push('C');
break;
}
}
// Reverse and rejoin the the string
return reverseC.join('');
}
var dnaSequence = prompt("Enter your DNA sequence here", "");
var newSequence = reverseComplement(dnaSequence);
alert("here is your reverse complemented DNA: " + newSequence);
The main lesson you need here is how to test and debug your JavaScript code.
First, get familiar with the JavaScript debugger in your browser. Instead of wondering why your code doesn't work, you can see directly what it is doing. Every modern browser has built-in JavaScript debugging tools; for example here is an introduction to the Chrome DevTools.
Second, when you are testing a function like this, don't use prompt() or alert(). Instead, provide a hard coded input string and use console.log() to display the output in the JavaScript debug console. This way you can run the same test case repeatedly. After you get one test case to work, you can add others.
There are several JavaScript testing frameworks if you want to get fancy, but to start with, simply using a hard coded input and console.log() output plus inspection in the JavaScript debugger is fine.
To make it easy to debug a function when you first write it, add a debugger; statement at the beginning. Then it will stop in the debugger and you can single-step through the code to see which parts of your function actually get executed and what all your variable values are at each step of the way.
For example (since it sounds like you were mistakenly testing with lowercase input), you might do this:
var dnaSequence = 'actg';
var newSequence = reverseComplement(dnaSequence);
console.log(newSequence);
function reverseComplement(dnaString) {
debugger;
var reverseC = [];
var dnaArr = dnaString.split('');
for (var i = 0; i < dnaArr.length; i++) {
switch (dnaArr[i]) {
case 'A':
reverseC.push('T');
break;
case 'T':
reverseC.push('A');
break;
case 'C':
reverseC.push('G');
break;
case 'G':
reverseC.push('C');
break;
}
}
// Reverse and rejoin the the string
return reverseC.reverse().join('');
}
Now, if you have the DevTools open, it will stop in the debugger at the first line of your function. You can single-step through the function to see which of the case statements it actually goes to, and you will see that it doesn't go to any of them. You can also look at the value of dnaArr[i] and see whether it matches any of the case values.
i need to identify the data/text being submitted from <input> if it contains any of the following. youtube, vimeo,normal website, jpg/png, plain text
if a youtube link is found {
//do something
} else if a vimeo link is found {
//do something
} else if a normal website is found {
//do something
} else if a (jpg/png) is found {
//do something
} else just a text {
} //do something
as of the moment is my syntax. the youtube & vimeo regex format were taken from other posts. but im not sure how to create the proper regex for the others.
ive tried some regex generator but its so complicated to use
im also interested to know if this is the proper way of executing multiple conditional statement.
$(function() {
$(document).on('click','.submit', function () {
var data = $('#input').val();
var youtube = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var vimeo = /^(http\:\/\/|https\:\/\/)?(www\.)?(vimeo\.com\/)([0-9]+)$/;
if (data.match(youtube)) {
alert("utube");
}
else if (data.match(vimeo)) {
alert("vimeo");
}
else if ...
});
});
There is a million different ways to do this.
The other regex you need are roughly bellow. Also it will save you a bit of a headache if you lowercase your data
var data = $("#input").val.toLowerCase();
Web url
/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/
PNG / JPG is at end of the string
/(png|jpg|jpeg)$/
Plain text i guese would be what ever is left
The most efficient way is also to use a switch statement not a big if else
like this http://www.w3schools.com/js/js_switch.asp
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
I would suggest using a switch statement when you have multiple regex conditions to check for:
var data = $('#input').val();
var youtube = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var vimeo = /^(http\:\/\/|https\:\/\/)?(www\.)?(vimeo\.com\/)([0-9]+)$/;
var normalWebsite = /^(?:ftp|http|https):\/\/(?:[\w\.\-\+]+:{0,1}[\w\.\-\+]*#)?(?:[a-z0-9\-\.]+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:\.\?\+=&%#!\-\/\(\)]+)|\?(?:[\w#!:\.\?\+=&%#!\-\/\(\)]+))?$/;
var image = /<img\s+src\s*=\s*(["'][^"']+["']|[^>]+)>/;
switch (true) {
case youtube.test(data):
alert('youtube');
break;
case vimeo.test(data):
alert('vimeo');
break;
case normalWebsite.test(data):
alert('normal website');
break;
case image.test(data):
alert('image');
break;
default:
// Here we are assuming anything that doesn't match the above is plain text.
// You will need an additional regex if you want to make sure this doesn't contain html or code.
alert('Plain text');
break;
}
I have been looking in both Jmeter and Javascript forums and can't figure out why this case statement is always matching to the default and I wondered if it was a Jmeter condition that I was missing.
I don't think it is a data problem. The URLTYPE_ variable is being set by a CSV input. Here are two lines from it.
Thumbnail,XXXXXX/XXXXXX,
Caption,XXXXXXXX/XXXXXX,
Code Snippet :
var t = vars.get("URLTYPE_");
log.info("starting");
log.info(t);
switch (t)
{
case "Thumbnail":
vars.put("CGIURL", "thumbres");
vars.put("LBURL", "thumb");
log.info("thumb");
break;
case "Caption":
vars.put("CGIURL", "capt");
vars.put("LBURL", "c");
log.info("c");
break;
default:
vars.put("CGIURL", "thumbres");
vars.put("LBURL", "thumb");
log.info("Default");
break;
}
log.info("stopping");
Try using if clauses instead of case with == comparison.
i am currently working on a simple ipad webapp testpiece and got stuck in a simple switch statement that doesn´t work somehow;
i want to format elements according to javascripts window.location string. This might be embarassing simple to fix; but i somehow don´t get it:
Or is there something special about the window.location?
$(document).ready(function() {
path_c = window.location;
switch (path_c){
case "http://192.168.1.37/ryba_testground/":
$('#menu-item-22').addClass('current_page_item');
alert(path_c);
break;
case "http://192.168.1.37/ryba_testground/?page_id=7":
$('#menu-item-21').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=9":
$('#menu-item-20').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=11":
$('#menu-item-19').addClass('current_page_item');
break;
}
});
THX!
Or is there something special about the window.location?
It's a host object, which sometimes act unpredictable. At least, it is an object which evaluates to the href when casted to a string - yet that does not happen when comparing with the switch-cases. Use
var path_c = window.location.href;
window.location returns a Location object, which contains information about the URL of the document and provides methods for changing that URL. So change it to:
var path_c = window.location.href;
I think you want the href property of the window.location object.
path_c = window.location.href;
Full Script
$(document).ready(function() {
path_c = window.location.href;
switch (path_c){
case "http://192.168.1.37/ryba_testground/":
$('#menu-item-22').addClass('current_page_item');
alert(path_c);
break;
case "http://192.168.1.37/ryba_testground/?page_id=7":
$('#menu-item-21').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=9":
$('#menu-item-20').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=11":
$('#menu-item-19').addClass('current_page_item');
break;
}
});
Example: http://jsfiddle.net/9vjY9/
The code seems ok. Try to alert (window.location.href) or console.log(window.location.href), then you can check exactly what does window.location.href gets for each page you test. This might reveal the problem.
You can use window.location.toString() or window.location.href, you even can avoid using switch, with a object map and regular expression to filter your target in url:
var page_idMap = {
'7': '#menu-item-21',
'9': '#menu-item-20',
'11': '#menu-item-19'
}
var id = window.location.href.match(/page_id[=]([0-9]+)/i);
if (!id || !page_idMap(id[1])) {
$('#menu-item-22').addClass('current_page_item');
} else {
$(page_idMap[id[1]]).addClass('current_page_item');
}