i'm searching for an equivalent function for php's "list()". i'd like to split a string with "split()" and put the array values in two different variables. hopefully there's another way to do this as short and performance-optimized as it could be.
thanks for your attention!
Here's a list implementation in javascript:
http://solutoire.com/2007/10/29/javascript-left-hand-assignment/
Maybe PHP.JS is worth looking at (for future stuff maybe). I noticed that the list() was only experimental though but maybe it works.
If you can live without the naming, you can do this:
var foo = ["coffee", "brown", "caffeine"];
foo[0] + " is " + foo[1] + " and " + foo[2] + " makes it special";
Alternatively, use a object to name the keys:
var foo = {drink: "coffee", color: "brown", power: "caffeine"};
foo.drink + " is " + foo.color + " and " + foo.power + " makes it special";
I think the closest you can get is the explicit
var args = inputString.split(",");
// Error checking, may not be necessary
if (args.length < 3)
{
throw new Error("Not enough arguments supplied in comma-separated input string");
}
var drink = args[0];
var color = args[1];
var power = args[2];
since Javascript doesn't have multiple assigment operators. I wouldn't worry too much about the efficiency of this; I expect that the list function in PHP basically boils down to the same thing as above, and is just syntactic sugar. In any case, unless you're assigning hundreds of thousands of variables, the time to execute anything like the above is likely to be negligible.
Related
I have tried for so long to get this code to work. I'm programming a little game when you need to be fast, so I made a stopwatch. But the stopwatch just doesn't want to work. Instead of the seconds the stopwatch is showing Object Undefined and I don't know why. This is the code i'm using:
var stopwatchFrame = 0;
var stopwatchSeconds = 0;
var stopwatchSecondsString = "Nothing";
stopwatchFrame+=1;
stopwatchSeconds = floor(stopwatchFrame/updatesPerSecond);
stopwatchSecondsString = toString(stopwatchSeconds);
var = "Total time: " + stopwatchSecondsString + " seconds";
I'm using a simple website called Koda.nu, it's a Swedish website for young to learn programming in JS. Some functions is coming from their built in source. I'm new to programming so that's why.
You are missing a variable name where you have a value of "Total time: " + stopwatchSecondsString + " seconds"; It should be:
var totalTime = "Total time: " + stopwatchSecondsString + " seconds";
Also read what #Jaromanda X wrote in the comments section. It should be like this:
stopwatchSeconds = Math.floor(stopwatchFrame/updatesPerSecond);
stopwatchSecondsString = stopwatchSeconds.toString();
We don't have an access to your updatesPerSecond variable so that would throw an error as well. If declared, your code would work like this:
var stopwatchFrame = 0;
var stopwatchSeconds = 0;
var stopwatchSecondsString = "Nothing";
var updatesPerSecond = 0;
stopwatchFrame += 1;
stopwatchSeconds = Math.floor(stopwatchFrame / updatesPerSecond);
stopwatchSecondsString = stopwatchSeconds.toString();
var totalTime = "Total time: " + stopwatchSecondsString + " seconds";
You dont have a variable name in the last line, and if this is all your code, then you dont initialize updatesPerSecond, meaning you dont have a line like
var updatesPerSecond = somenumberhere
If you name your last variable and initialize updatesPerSecond then you should be fine.
However I dont know anything about this website, but I quess it's old. Here is some advice.
You need to tell javascript, that floor is a function from Math so use Math.floor, maybe it works in this website like you did, but keep in mind that you should use it otherwise.
toString() doesnt work like that. Again I dont know if they are using some different methods, but normal js toString() works like number.toString() and u can pass the radix as a parameter, meaning the base of the number representation (2 for binary, 16 for hexadecimal etc.) but this is optional, default is 10 for decimal.
Dont use var as a declaration. Use let instead, if the variable will change, and use const if it wont. In your case you should use let everywhere.
Other thing is that you can use the ++ operator to increment a value by 1, so instead of stopwatchFrame+= 1 just use stopwatchFrame++
And last you shouldn't initialize your default string value as "Nothing", it should be "", an empty string or undefined or null.
I hope this helps, have a good day!
I have few specific questions regarding function usage.
My apologies if it seems too basic to ask here. I am working on an ever growing project. These questions have been bothering me a lot lately.
Questions:
1. Do I need to validate arguments in every single function?
//getConcatInfo: ("John Doe", 50, {name: "London"}) => "John 50 London"
getConcatInfo(name, age, city){
let first = name.split(" ")[0];
return first + " " + age + " " + city.cityName;
}
Should I check if each argument exists or not in every single function that I have in my project?
Should I check if each argument is the right type or not, for all functions? For example city should be an object with key cityName and name and age should be String and Number
If, say, two arguments exist and third doesn't should I throw an exception or just return null. The reason for asking this is, libraries like RXJS, will stop listening to a given event the moment any error is thrown inside that event handler
2. Do I need to validate argument before calling a function?
let name = user.name;
let name = user.age;
let city = getUserCity();
if(name && age && city && city.name) //<= like this?
getConcatInfo(name, age, city);
My question is: Do I go by approach 1 or 2 or both?
You should never trust input. You should check your arguments inside the function.
You have control over the function but no control over the calling sites.
Regarding how much checks you should do. This depends on your use case. Too few checks and you may end up with a lot of runtime problems, too much checks and you'll ship a lot slower, so it is up to you to figure out what is too much. A rule of thumb you can apply is that the more control you have over the calling sites less checks you can do inside the functions, but you should not trust input.
Returning null (or another value) or throwing an exception depends on how big the violation you get in your params. You can try to recover from minor problems: by returning null or using a default value for the specific param and execute your code. If you cannot recover from the error then you should throw an exception. In your case you could do something like this
getConcatInfo(name, age, city){
name = name || 'default name'
age = age || 18
city = city || {cityName: 'default name'}
let first = name.split(" ")[0];
return first + " " + age + " " + city.cityName;
}
you could also use default params
getConcatInfo(name = 'default name', age = 18, city = {cityName: 'default name'}){
let first = name.split(" ")[0];
return first + " " + age + " " + city.cityName;
}
If you want type check you may want to look into TypeScript. But of course, this is a different language:)
I am trying to load a javascript in WebView to do some calculations and get the output in a string. I tried to use following code
string htmlFragment = "<html><head><script type='text/javascript'>" +
"function doubleIt(incoming){ " +
" var intIncoming = parseInt(incoming, 10);" +
" var doubled = intIncoming * 2;" +
" document.body.style.fontSize= doubled.toString() + 'px';" +
" return doubled.toString());" +
"};" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
htmlView.NavigateToString(htmlFragment);
htmlView.LoadCompleted += async(s1,e1) =>
{
string result = await htmlView.InvokeScriptAsync("eval", new string[] { "doubleIt(25)" });
Debug.WriteLine(result);
};
Update
I am able to load simple javascript easily now based on help provided in the answer. But now I am facing issues when there is more than one function in javascript, I am getting an exception. I am trying the following code
string htmlFragment = #"<html><head><script type='text/javascript'>" +
"function a(){return 10;};" +
"function b(){return 20;};" +
"function c(){return 30;};" +
"return (a()*b()*c());" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
Please suggest.
The documentation for this feature is really poor. It took me some time to figure out how to invoke Javascript in UWP WebView
When you first look at the function call webView.InvokeScriptAsync(string,string[]) your initial reaction is that they want the function name as the first parameter and then the function paramaeters as the string array. (mainly because the MSDN documentation says this)
Parameters
scriptName
Type: System.String [.NET] | Platform::String [C++]
The name of the script function to invoke.
arguments
Type: System.String[]
[.NET] | Platform::Array [C++]
A string array that
packages arguments to the script function.
HOWEVER, this is wrong and will lead to hours of head banging. REALLY, what they want is the word "eval" in the first parameter and then a string array of functions, and or commands you wish to eval
var value = await webViewer.InvokeScriptAsync("eval",
new string[]
{
"functionName(functionParams)"
});
Having worked with Microsoft APIs for a few years now I am convinced that this is not the intended way of consuming this function and is a bit of a hack. Unfortunately if you want to consume JavaScript this is the only way that I know that works currently.
Anthony,
Try to check your own suggestion:
await webViewer.InvokeScriptAsync("eval",
new string[]
{
"functionName(functionParams)"
});
or:
await webViewer.InvokeScriptAsync(functionName, new string[]{ functionParameters });
The same as Microsoft suggests, just you are limiting a function name by one ("eval") - not necessary. Trust me, you can use any function name, as I am now with UWP and before with windows phone hybrid apps.
The question is already 4 years old, but I'm coming to see why you were getting an empty string as a result.
In your example, the functions in JavaScript return integers while the expected value is of type string.
By modifying these functions and returning a string like this:
string htmlFragment = #"<html><head><script type='text/javascript'>" +
"function a(){return '10';};" +
"function b(){return '20';};" +
"function c(){return '30';};" +
"</script></head><body>" +
"<div id = 'myDiv'>I AM CONTENT</div></body></html>";
We get the good result on the way back.
I am very new to learning both Javascript and Jquery.
In the website I am creating I am trying to insert a Javascript if statement and a for loop in a line of JQuery. The last confirm does not run. I suspect it is the if statement that is causing the issue. How can I fix this? Here is how my code looks like.
$(document).ready(function() {
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
confirm("You're last name is" + " " + lastname);
if (userResponse = "girl") {
for (var i = 0; i <= girlnames.length; i++) {
confirm("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
})
});
There's a lot that doesn't make much sense with your code.
First, what is userResponse? Where does this get defined and where is it set? Have you verified under a debugger that it is indeed equal to "girl"?
Second, you probably meant to use a comparison equals not an assignment equals here:
if (userResponse = "girl") { // This should be ==
However, this should not prevent the block from running. In fact, it will force the block to always run since "girl" is true-ish.
Third, what is girlnames? Is it an array? Where is this defined? Have you verified it indeed contains valid items?
Lastly, I believe your for loop is incorrect:
for (var i = 0; i <= girlnames.length; i++) {
Should be:
for (var i = 0; i < girlnames.length; i++) {
Arrays start at 0, thus girlnames[girlnames.length] is not a valid item.
However, considering you don't use the i variable in your loop anywhere, again this should not actually cause any errors.
I would step through your code line by line using a script debugger (usually F12 in modern browsers) and set a break point at:
var lastname = $('#lastnameresponse').val();
Then verified each line is behaving correctly. If that still doesn't work, you'll need to post more of your code so we can get a better idea of what's going on.
UPDATE:
Based on your comment:
Here is where the userResponse variable is defined:
$(document).ready(function(){ $("#girlimg").click(function() { var
userResponse = prompt("Confirm the gender you selected").toLowerCase;
$('html, body').animate({ scrollTop: $(".LastName").offset().top },
2000);
It seems that userResponse gets declared within the click handler for the #girlimg tag:
$("#girlimg").click(function() {
// Everything declared here is local to this function
var userResponse = confirm(); // local variable
});
Thus, it would not be accessible in the click handler for .button3. You'll need to declare userResponse in a scope that is accessible to both functions. Perhaps global (this is frowned upon in JavaScript) or within your $(document).ready() code, provided both click event handlers are defined within that block.
First: it's Your not You're :)
Secondly, userResponse is undefined. Maybe it's defined somewhere else.
For comparison, use == operator.
Are you sure is that what you want to do? I see you also have confirm there.
Use confirm like this:
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
// confirm() returns true or false, depending on the clicked button
is_confirmed = confirm("You're last name is" + " " +lastname);
if (true == is_confirmed) {
for (var i = 0; i <= girlnames.length; i++) {
confirm ("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
}
}
});
girlnames is also not defined here (maybe it's somewhere else). Same for random and randomagain
As for writing JavaScript "in" jQuery: there is no such question. jQuery is a library written in Javascript that provides useful functions to ease development.
Following statement does not contain a proper JavaScript Comparison Operator
equals is written ==
if (userResponse = "girl") {
for reference look here
you forgot to close some arrows, any way when you put :
if (userResponse ="girl"){...}
you set userResponse variable to "girl", and that passes the value to the variable only
to check in the userResponse is equal to "girl" you should put
if (userResponse =="girl")
your final code will look like this
$(document).ready(function(){
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
confirm("You're last name is" + " " +lastname);
if (userResponse ="girl") {
for (var i = 0; i <= girlnames.length; i++) {
confirm ("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
}}}
)
});
p.s:you forgot to close too many arrows
my name's Mike and my question is two-fold:
How can I access the objects in my array so that they properly appear in my question prompt, and
How can I access the properties of the randomely selected object in an if/else statement?
I'm trying to make a simple flashcard program to help me memorize different kinds of sound equipment. The list of equipment is large but I'm only including three different kinds to keep this example simple. I want each object to have two properties: answer and desc. This first part defines three objects, places them in an array, creates a variable for picking one of the array items randomely, and another variable for prompting the user for an answer:
var newFlash = function() {
var A827 = {
answer: "T",
desc: "Multitrack Tape Recorder"
};
var LA2A = {
answer: "O",
desc: "Classic Leveling Amplifier"
};
var SonyC800G = {
answer: "M",
desc: "Tube Condenser Microphone"
};
var list = [A827, LA2A, SonyC800G];
var rand = Math.floor(Math.random() * list.length);
var question = prompt("What kind of equipment is " + list[rand] + "?");
};
Now, if I make my three items in my array all strings, they show up no problem in the question prompt correctly replacing list[rand] with the appropriate array item. However, using objects in my array, my prompt says "What kind of equipment is [object Object]?.
My end goal is for the user to enter the appropriate one- or two-letter response (M for Microphone, C for Console, O for Outboard Gear, T for Tape Machine, S for Software, and CH for Computer Hardware) where upon entering the successful letter(s) yields an alert that displays both the object's answer and desc. My n00b instinct tells me this second part should be an if/else statement in the form of
if (question == list[rand.answer]) {
alert("Correct, Answer: " + list[rand.answer] + ", a " + list[rand.desc] + "!");
}
else {
alert("Wrong, try again.");
}
but I'm very certain that this isn't the right way to access these object properties.
So, again, my question has two parts:
How can I access the objects in my array so that they properly appear in my question prompt, and
How can I access the properties of the randomely selected object in an if/else statement?
I'm sure some piece of logic is escaping me. Thanks for reading.
You want to use var question = prompt("What kind of equipment is " + list[rand].desc + "?");. list[rand] will yield you an object which has the structure {answer: "", desc: ""}, so you need to additionally access the description in your code.
Similarly, you want:
if (question == list[rand].answer) {
alert("Correct, Answer: " + list[rand].answer + ", a " + list[rand].desc + "!");
}
else {
alert("Wrong, try again.");
}
To access the property of an Object in Javascript you use dot notation, as is common with many languages that have Objects. list is an array of Objects, so when you type list[rand] you are returning one of those Objects. Once you have an Object, you simply need to use the dot notation to access whatever property it is you require, in this case either desc or answer.
So instead of
var question = prompt("What kind of equipment is " + list[rand] + "?");
try
var question = prompt("What kind of equipment is " + list[rand].desc + "?");
Placing the property you are trying to access outside the bracket. This solves your second question as well, simply change:
if (question == list[rand.answer]) {
alert("Correct, Answer: " + list[rand.answer] + ", a " + list[rand.desc] + "!");
to:
if (question == list[rand].answer) {
alert("Correct, Answer: " + list[rand].answer + ", a " + list[rand].desc + "!");
this fiddle will help demonstrate.