Return JSON value from a function - json

I am able to pass a JSON string to my function but can't return a value back.
var json = {"First":"ABC", "Middle":"DEF", "Last":"GHI"};
allFunction6(json);
alert(first); //this does not work
function allFunction6(json) {
var first = json.First;
alert(first); //this alerts "ABC"
return first;
}
Does the variable not retain its value outside of the function, or am I missing something?
Thanks.

Nope, the variable does not retain its value outside of the function, because that is where it is scoped to, the function.
You need to save the returned value.
var storedReturnValue = allFunction6(json);

Related

How can I keep an array filled outside of a function?

This question is part of finding a solution to a larger problem. However, I am wondering if there is a way to use a function to fill an Array. Based on the test code below, it seems arrays automatically empty after the function. I am looking to have a function that fills the array repeatedly, and another one that triggers to paste the resulting array.Note the paintArray=[] defined outside of the functions.
The console logs '1' for fillArray() but when I run logArray() right after it logs [].
const paintArray = []
function logArray(){
console.log(paintArray)
}
function fillArray(){
paintArray.push(1)
console.log(paintArray)
}
You can use Properties Service this way:
var scriptProp = PropertiesService.getScriptProperties();
function logArray(){
Logger.log(scriptProp.getProperty("paintArray"))
}
function fillArray(){
var obj = scriptProp.getProperty("paintArray")
if(obj){ //check if paintArray Object exists
var arr = JSON.parse(obj); //parse the value to array
arr.push(1); //push value 1
scriptProp.setProperty("paintArray", JSON.stringify(arr)) //set new value of arr to properties
}else{
scriptProp.setProperty("paintArray", "[1]"); //set initial value if paintArray object is undefined
}
}
First run:
Second run:
Third run:
Save and Retrieve Array from Properties Service
function saveArray(a) {
PropertiesService.getScriptProperties().setProperty("myarray",JSON.stringify(a));
}
function getArray() {
return JSON.parse(PropertiesService.getScriptProperties().getProperty("myarray"));
}

What does this conf do?

So I was looking at a tutorial online and came across this:
function generateRobot(conf:Object = null):Robot {
var conf:Object = conf || {};
var defaults:Object = {
laserColor:red,
personality: "evil"
}
for (var key:String in defaults){
conf[key] = conf[key] || defaults[key];
}
Can someone help explain what line 2 and line 8 mean? Thanks for helping a new coder!
I have added some comments and renamed the param to make it clearer:
//param is a parameter of the type object with a default value of null that is passed
//into the function, if nothing is passed in it will be null
function generateRobot(param:Object = null):Robot {
//declare a local variable called conf and populate
//it with the parameter if it exists, otherwise create a new object {}
var conf:Object = param || {};
//create a default settings object
var defaults:Object = {
laserColor:red,
personality: "evil"
}
//loop through the default settings
for (var key:String in defaults){
//conf setting becomes param if exists otherwise use the defaults value
conf[key] = conf[key] || defaults[key];
}
The questions seems specific to the || construct in the variable assignment. As #Thilo mentioned, it is simply a way to specify a default, should the field be missing in the parameter.
For example:
function read_file(file, delete_after) {
delete_after = delete_after || "False";
//rest of code
}
would be such that, if variable delete_after is not passed when function read_file is called, then it will assume value "False", or anything after the || sign.
Some prefer an explicit check against undefined.
Other pointers to look at:
Set a default parameter value for a JavaScript function
http://www.codereadability.com/javascript-default-parameters-with-or-operator/

nightwatch.js return value from function outside a test

I have trouble moving certain code outside a test into a function that needs to return a value.
Here is part of my code for the test file
function getCountOfTopics(browser){
var count;
browser.getText('#sumTopics',
function(result){
count = result.value;
console.log(result.value);
}
);
return count;
};
module.exports = {
'Create article' : function(browser){
var noOfThreadsByInlineCode, noOfThreadsByFunction;
browser.getText('#sumTopics',
function(result){
noOfThreadsByInlineCode = result.value;
}
);
noOfThreadsByFunction = getCountOfTopics(browser);
browser.end();
}
}
Now, the variable noOfThreadsByInlineCode indeed gets the value in the DOM, but the variable noOfThreadsByFunction is undefined. The console does indeed print the correct value, so the function does get the correct value out of the DOM.
I would appreciate help in updating the function so that I do get the value returned.
One word answer is Asynchronisity. The code doesn't wait for your callback to get complete, thats what the feature of Node JS is.
If you are in desperately in need for the content inside of the callback you can write this variable into a file and then access it anywhere you want inside your code. Here's a bit of a workaround:
Save something in a file:
var fs = require('fs');
iThrowACallBack(function(response){
fs.writeFile('youCanSaveData.txt', this.response, function(err) {
if (err) throw err;
console.log('Saved!');
browser.pause(5000);
});
});
Access it somewhere else:
iAccessThefile(){
response = fs.readFileSync('youCanSaveData.txt').toString('utf-8');
}
Hope it helps.
You return variable 'count' outside the callback,that is why.You can take a look this topic How to return value from an asynchronous callback function?
function getCountOfTopics(browser){
var count;
browser.getText('#sumTopics',
function(result){
count = result.value;
console.log(result.value);
/// result.value is available in this callback.
}
);
What do you want to do with the 'value'?
ps:do not remember custom_command.I think it is very helpful for this issue.

Is is possible to pass a string object inside another object?

I have a string and i would like to pass it by reference in a object.
var str:String = '';
var object:Object = {s:str};
object.s = 'test';
trace(str); // i would like this to output test but it is just blank
trace(object.s); //this has a value stored in it
Is this possible or am i thinking about this wrong?
What i am trying to do is update the str value by updating object.s. I want the sting object to be inside the object not the value of the str.
I want it to do something more like this
var obj2:Object = new Object();
obj2.txt = '';
var object:Object = {s:obj2};
object.s.txt = 'test';
trace(obj2.txt); // outputs test
trace(object.s.txt); //outputs test
Of course it is possible. In the above example i suspect the trace works fine, but since there is no value, it does not display anything. I don't know actionscript very well, but since it compiles down to javascript then all objects are passed by reference. your example code actually has two objects in it one called string that is a string with no value assigned, and the other an object with a property called s that is a string. that it why there is no output.
var string:String = '';
var object:Object = {s:string};
object.s = 'test';
string = object.s;
trace(string); // i would like this to output test but it is just blank
trace(object.s);
This should show you what you want to see, and is passed by reference, unless actionscript enforces pass by value, which i do not believe it does

How to Getting the Variable from Function in as3 without using get ,set method?

Hai am Getting trouble to retrive the values from function(addText).i Called from another function onFullScreen().I dont know how Can i do this,Kindly Help me?Here i attach my Code
private function addText()
{
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, ncOnStatus);
function ncOnStatus(infoObject:NetStatusEvent)
{
trace("nc: "+infoObject.info.code+" ("+infoObject.info.description+")");
if (infoObject.info.code == "NetConnection.Connect.Success")
{
initSharedObject(chatSharedObjectName);
}
}
function formatMessage(chatData:Object)
{
trace("room"+chatData.message);
number = chatData.txtalign;//i want to retrive the value of number
number.toString();
return number;
}
function syncEventHandler(ev:SyncEvent)
{
var infoObj:Object = ev.changeList;
// if first time only show last 4 messages in the list
if (lastChatId == 0)
{
lastChatId = Number(textchat_so.data["lastChatId"]) - 1;
if (lastChatId < 0)
lastChatId = 0;
}
}
function connectSharedObject(soName:String)
{
textchat_so = SharedObject.getRemote(soName, nc.uri)
// add new message to the chat box as they come in
textchat_so.addEventListener(SyncEvent.SYNC, syncEventHandler)
textchat_so.connect(nc)
}
function connectSharedObjectRes(soName:String)
{
connectSharedObject(soName)
trace(soName)
}
function initSharedObject(soName:String)
{
// initialize the shared object server side
nc.call("initSharedObject", new Responder(connectSharedObjectRes), soName)
}
}
i using the variable in another function ,but I cannot retrive the Value.
private function onFullScreen(event:FullScreenEvent):void
{
mediaContainer.addMediaElement(alert);
alert.alert("Error",number);// if i cannot retrive the value hnumber here
}
The addText() method is asynchronous, meaning that you can't simply call it , you need to wait for the event listener to return a value.
I'm not sure why you would feel the need to enclose all these functions, it's not very legible and I doubt it's necessary. You're also missing quite a few semi colons...
In any case , I couldn't see where the formatMessage() method was called, it seems that's the only place where the "number" variable gets defined.
You could create a variable outside the scope of the functions.
private var num:int;
Then in your addText function, assign a value to the variable:
num = infoObject.info.code;
Then in your onFullScreen function, access the num variable:
alert.alert("Error", num);