Passing value from inside of function to a parameter in JavaScript - javascript

I have a function that replaces characters from a string
function ratko(a) {
var k = a.toString();
var z = k.replace(/\,/g, '], [');
var s = z.replace(/\./g, ', ');
var final = "[[" + s + "]]";
alert(final);
}
What I need is to get the value of final outside the function like this:
var outsideValue = final;
EDIT!!! --
function ratko() gets it's value from ajax
success: function (data) {
if (data.success) {
alert("Note: This month has " + data.holidays.length + " holidays.");
praznici = data.holidays;
ratko(praznici);
}
else {
alert(data.ErrorMessage);
}

Possibility 1:
function ratko (a) {
...
return final;
}
var outsideValue = ratko (...);
Possibility 2:
var final;
function ratko (a) {
// no var final declaration here
...
}
...
ratko (...);
// now final has the value assigned to it in the function
You can access variables declared in an outer scope in an inner scope, which is what you do in Possibility 2.

One option would be to use a global variable, just declare it outside of the function.
var myvar = 1;
function myFunction()
alert(myvar); // 1
}
You can read more on javascript variables here.

You declare it outside the function scope:
var finalVar;
function ratko(a) {
var k = a.toString();
var z = k.replace(/\,/g, '], [');
var s = z.replace(/./g, ', ');
finalVar= "[[" + s + "]]";
alert(finalVar);
}
var outsideValue = finalVar;
Beware final is a reserved keyword in Javascript. I changed its name.
Besides that, keep in mind that Javascript is always parsed from top to bottom. So using a variable before declaring it will definitely give you an undefined.

you must be modify your function code like this
function ratko(a) {
var k = a.toString();
var z = k.replace(/\,/g, '], [');
var s = z.replace(/./g, ', ');
var final = "[[" + s + "]]";
//alert(final); comment this code line and replace this with the code above
return final;
}
after you can call your function ratko with this simple code
var inputValue = 'simple message';
var parsedValue = ratko(inputValue);
you find the final value into a new variable parsedValue

Related

Getting undefined value when trying to use with inner functions

Following is my code snippet :
function executorFunc(input){
return input();
}
function mainFunc(){
var a = 100;
function innerFunc(){
var b = 20;
return a + b;
}
executorFunc(innerFunc);
}
var finalVal = mainFunc();
console.log(finalVal);
I was in the assumption that innerFunc gets created within mainFunc and will be aware of outer/enclosing functions data like a = 100. To my surprise, it's not. There is something that is doing it wrong or there is something which I have misunderstood in basics of JS.
The final output is undefined where I was expecting 120.
Expected result as you are not returning the value from mainFunc function().
Use
return executorFunc(innerFunc);
function executorFunc(input){
return input();
}
function mainFunc(){
var a = 100;
function innerFunc(){
var b = 20;
return a + b;
}
return executorFunc(innerFunc);
}
var finalVal = mainFunc();
console.log(finalVal);
The problem here is that mainFunc does not return any value. So finalVal remains undefined.

How to create elements inside a loop and store them into a variable in JavaScript to be accessed outside the loop

I want to create some elements of a particular number, inside a loop, store them in a variable, then access that variable outside that loop.
The reason I want to access that variable outside the loop is so that I can put them inside an append function.
function range(start, stop, step) {
var a = [start],
b = start;
while (b < stop) {
b += step;
a.push(b);
}
return a;
}
var yAxis = range(1, 100, 10);
$.createAxis = function(axisValues) {
$(axisValues).each(function(index, element) {
yAxisNav = document.createElement('div');
var newValue = document.createTextNode("I have content!");
yAxisNav.appendChild(newValue);
return yAxisNav.className = 'graphBar_yAxis_label';
});
}(yAxis);
console.log(yAxisNav);
//$('body').append('<section>'+yAxisNav+'</section>');
The above only returns one element, how can I store this so that its accessible outside that loop?
As you wants to return a list of div's, I have moved yAxisNav outside function and appending it with every loop.
I think you are looking for this...
var yAxisNav = "";
$.createAxis = function (axisValues) {
$(axisValues).each(function (index, element) {
var elem;
elem = document.createElement('div');
var newValue = document.createTextNode("I have content!");
elem.appendChild(newValue);
elem.className = 'graphBar_yAxis_label';
yAxisNav += elem.outerHTML;
});
return yAxisNav;
}(yAxis);
console.log(yAxisNav);
$('body').append('<section>'+yAxisNav+'</section>');
Get the value returned by createAxis
return yAxisNav object from the function. This should be the last statement in the function createAxis,
return yAxisNav;
And then you can get it as follow:
var yAxisNav = $.createAxis(something);
CODE
$.createAxis = function(axisValues) {
$(axisValues).each(function(index, element) {
yAxisNav = document.createElement('div');
var newValue = document.createTextNode("I have content!");
yAxisNav.appendChild(newValue);
yAxisNav.className = 'graphBar_yAxis_label'; // Move up
return yAxisNav; // Return complete object
// ^^^^^^^^^^^^^
});
}(yAxis);
As mentioned here, define the variable in the highest scope in which you want to access it.
In this case, define it outside the range function.

Error in my closure

JS Bin example
Why does it not count, my output is always 1 in the console. I am new to closures and I must be missing something simple? Here is the code from the jsbin:
var counterFunc = function()
{
var count = 0;
var incCount = function()
{
count = count + 1;
return count;
};
return incCount();
};
var myCounter = counterFunc;
console.log(myCounter());
console.log(myCounter());
By returning incCount() - the result of the invocation - from your counterFunc, you're not really creating a closure function. You want to return a function, and invoke the counterFunc() to create it:
var counterFunc = function() {
var count = 0;
var incCount = function() {
count = count + 1;
return count;
};
return incCount ;
// ^
};
var myCounter = counterFunc();
// ^^
console.log(myCounter());
console.log(myCounter());
You should be returning the inner function itself, not the result of calling it
You therefore need to replace return incCount() with:
return incCount;
You subsequently need to directly invoke counterFunc() when you declare myCounter:
var myCounter = counterFunc(); // myCounter is now the closure
Only then will myCounter be assigned a reference to the inner function, that happens to hold a "closure" over the local variable count.

How to get parameter value inside a string?

Here's a thing i've been trying to resolve...
We've got some data from an ajax call and the result data is between other stuff a huge string with key:value data. For example:
"2R=OK|2M=2 row(s) found|V1=1,2|"
Is it posible for js to do something like:
var value = someFunction(str, param);
so if i search for "V1" parameter it will return "1,2"
I got this running on Sql server no sweat, but i'm struggling with js to parse the string.
So far i'm able to do this by a VERY rudimentary for loop like this:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
var arr = str.split("|");
var i = 0;
var value = "";
for(i = 0; i<arr.length; ++i){
if( arr[i].indexOf(param)>-1 ){
value = arr[i].split("=")[1];
}
}
console.log(value);
if i put that into a function it works, but i wonder if there's a more efficient way to do it, maybe some regex? but i suck at it. Hopefully somebody may shine a light on this for me?
Thanks!
This seems to work for your specific use-case:
function getValueByKey(haystack, needle) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp(needle + '=(.+)');
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1');
console.log(test);
JS Fiddle demo.
And, to include the separator in your search (in order to prevent somethingElseV1 matching for V1):
function getValueByKey(haystack, needle, separator) {
if (!haystack || !needle) {
return false;
}
else {
var re = new RegExp('\\' + separator + needle + '=(.+)\\' + separator);
return haystack.match(re)[1];
}
}
var str = "2R=OK|2M=2 row(s) found|V1=1,2|",
test = getValueByKey(str, 'V1', '|');
console.log(test);
JS Fiddle demo.
Note that this approach does require the use of the new RegExp() constructor (rather than creating a regex-literal using /.../) in order to pass variables into the regular expression.
Similarly, because we're using a string to create the regular expression within the constructor, we need to double-escape characters that require escaping (escaping first within the string and then escaping within in the created RegExp).
References:
RegExp.
String.match().
This should work for you and it's delimiters are configurable (if you wish to parse a similar string with different delimiters, you can just pass in the delimiters as arguments):
var parseKeyValue = (function(){
return function(str, search, keyDelim, valueDelim){
keyDelim = quote(keyDelim || '|');
valueDelim = quote(valueDelim || '=');
var regexp = new RegExp('(?:^|' + keyDelim + ')' + quote(search) + valueDelim + '(.*?)(?:' + keyDelim + '|$)');
var result = regexp.exec(str);
if(result && result.length > 1)
return result[1];
};
function quote(str){
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
})();
Quote function borrowed form this answer
Usage examples:
var str = "2R=OK|2M=2 row(s) found|V1=1,2|";
var param = "V1";
parseKeyValue(str, param); // "1,2"
var str = "2R=OK&2M=2 row(s) found&V1=1,2";
var param = "2R";
parseKeyValue(str, param, '&'); // "OK"
var str =
"2R=>OK\n\
2M->2 row(s) found\n\
V1->1,2";
var param = "2M";
parseKeyValue(str, param, '\n', '->'); // "2 row(s) found"
Here is another approach:
HTML:
<div id="2R"></div>
<div id="2M"></div>
<div id="V1"></div>
Javascript:
function createDictionary(input) {
var splittedInput = input.split(/[=|]/),
kvpCount = Math.floor(splittedInput.length / 2),
i, key, value,
dictionary = {};
for (i = 0; i < kvpCount; i += 1) {
key = splittedInput[i * 2];
value = splittedInput[i * 2 + 1];
dictionary[key] = value;
}
return dictionary;
}
var input = "2R=OK|2M=2 row(s) found|V1=1,2|",
dictionary = createDictionary(input),
div2R = document.getElementById("2R"),
div2M = document.getElementById("2M"),
divV1 = document.getElementById("V1");
div2R.innerHTML = dictionary["2R"];
div2M.innerHTML = dictionary["2M"];
divV1.innerHTML = dictionary["V1"];
Result:
OK
2 row(s) found
1,2

If I have a variable, assigned to the value of a function call, can that variable be updated if the function call's parameters are changed?

If I have a function, like this:
function f(x,y){
return x + y;
}
And if I have variables of parameters I want passed to f:
var parameter1;
var parameter2;
If I assign this function call to a variable:
var functionCallValue = f(parameter1,parameter2);
How can I ensure that functionCallValue changes depending on different values I assign to the variable parameter1 and parameter2?
I suppose what you need is a closure.
var servant = function(x, y) { return x + y; };
var param1 = 40;
var param2 = 2;
var master = function() { return servant(param1, param2) };
var result = master(); // 42.
param1 = 2;
param2 = 40;
var anotherResult = master(); // still 42, because that's really the answer!
functionCallValue is assigned the result (returnvalue) of your function f. (The function is called, the value calculated and the result handed over to your variable.) Thus functionCallValue does not automatically update, if you change the parameters (which would make no sense at all), you need to call the function again with the altered parameters.
For something like an auto-update you need a closure like this:
var asdf = (function(){
var param1 = 1;
var param2 = 2;
var result = param1+param2;
function compute(){
result = param1 + param2;
}
return{
param1:function(x){
param1 = x;
compute();
},
param2:function(x){
param2 = x;
compute();
},
result:function(){
return result;
}
}
})();
console.log(asdf.result()); // logs 3
asdf.param1(3);
console.log(asdf.result());​ // logs 5
Demo

Categories

Resources