I'm a big noob at JS,so if my question is hard to understand then sorry😂.
I'm writing a program in JS(Electron) that provides a user interface for another program I made in C++, so I'm basically rewriting it in JavaScript.
I want to use this JSON variable(or whatever it's called) in my code.
var ShowSecondsInSystemClock = '{"name":"ShowSecondsInSystemClock","Description":"Patches the System Tray clock to show seconds","ExplorerRestartRequired":"true","category":"UI-Tweaks","badges":"UITweaks"}'
Then I would like to use this function where the parameter of the function "ShowSecondsInSystemClock" is.
function TweakParser(TweakName, NeeddedReturn) {
if (NeeddedReturn == "Description") {
//I'm trying to use TweakName as the parameter of parse(),but it only
//accepts the name of the Tweak directly
var NeeddedTweakInfo = JSON.parse(TweakName)
return NeeddedTweakInfo.Description
}
}
Because there will be many Tweaks, the usecase of this particular function is for example
//I use a non-existing tweak here for the example
TweakParser("RemoveArrowsFromShortcut","Description")
What I want TweakParser to do now is use RemoveArrowsFromShortcut as the parameter of JSON.parse() but it only accept the name of the JSON variable directly and when I input the name of the first parameter of the TweakParser() function it gives me an error, because the parameter(a variable) itself is not a JSON variable (or whatever it's called like).
So my question to you is:
How can I use the string that the first parameter of TweakParser() contains as a parameter for the JSON.parse() function?
You need to create mapping
like a schema 'key': variable
example:
{
'RemoveArrowsFromShortcut': ShowSecondsInSystemClock
}
Full example:
var ShowSecondsInSystemClock = '{"name":"ShowSecondsInSystemClock","Description":"Patches the System Tray clock to show seconds","ExplorerRestartRequired":"true","category":"UI-Tweaks","badges":"UITweaks"}'
var mapping = {
RemoveArrowsFromShortcut: ShowSecondsInSystemClock
};
function TweakParser(TweakName, NeeddedReturn) {
if (NeeddedReturn == "Description") {
var NeeddedTweakInfo = JSON.parse(mapping[TweakName]); // PAY ATTENTION HERE
return NeeddedTweakInfo.Description
}
}
var result = TweakParser("RemoveArrowsFromShortcut","Description")
console.log('result', result)
Related
I have an Array of Objects:
var keywordset = [
{word:["PO","Pending Order"],message:["Do you need to post registry?"]},
{word:["delete"],message:["Do you want to delete in system?"]},
{word:["contact"],message:["Inter-related feature: Contact Management"]}
]
Also, I created a function to convert the strings in an array of objects to UpperCase:
function ObjectArrayUpperCase(arrayname,array1){
console.log(arrayname[0])
console.log(array1)
for(b=0;b<arrayname.length;b++){
for(c=0;c<arrayname[b].array1.length;c++){
arrayname[b].array1[c] = arrayname[b].array1[c].toUpperCase()
}
}
}
Then, i run the ObjectArrayUpperCase() function by passing parameter into it
ObjectArrayUpperCase(keywordset,'word')
Unfortunately, the ObjectArrayUpperCase() function unable to process "array1" part, seems like unable to recognize it. But the "arrayname" working as expected, because if i replace "array1" to "word", the function work.
I tried to change the parameter but still no luck:
ObjectArrayUpperCase(keywordset,'word')
ObjectArrayUpperCase(keywordset,word)
ObjectArrayUpperCase(keywordset,keywordset.word)
etc...
Please advise how to pass the correct parameter to the function
You need square brackets to evaluate an expression like array1 to be used as the property name.
for(var b=0;b<arrayname.length;b++) {
// -----------------------v------v--- and likewise below
for(var c=0;c<arrayname[b][array1].length;c++){
arrayname[b][array1][c] = arrayname[b][array1][c].toUpperCase()
}
}
}
Otherwise, how could it know if you meant to use the variable or an actual property with that name?
Also, be sure to declare your variables explicitly. I used var above.
Lastly, the loops can be written a little more cleanly using modern syntax and methods like this:
arrayname.forEach(obj => obj[array1] = obj[array1].map(s => s.toUpperCase()))
I'm trying to setup a speed test for functions. It works when I pass in a function directly, but I'd like to offer co-workers a form to cut and paste their own.
function sendTest() {
//fName, fContent
var fName = document.getElementById("fName").value;
var fContent = document.getElementById("fContent").value;
var f = new Function(fName, fContent);
f.name = fName;
testTime(f);
}
testTime() is the function to evaluate performance, and evaluating time of execution is working correctly from sendTest(), but I can't access the function name from testTime() to display the function name with the results. f.name and f.fName both come up as undefined.
A function is an object, right? So I should be able to apply a name propery to it?
This seems like a much simpler answer for your specific problem than the what someone else marked your question a duplicate of.
In ES6, there is a built-in .name property of a Function which is NOT writable so that's why you can't assign to it (link to specific section of draft ES6 spec). You should be able to use a different property name if you want to assign a name the way you are doing so.
Working demo using a different property name: http://jsfiddle.net/jfriend00/6PVMq/
f = new Function("log('Hello')");
f.myName = "sayHi";
function testFunc(func) {
log("function name is: " + func.myName);
func();
}
testFunc(f);
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Get actual HTML values using javascript
so i have two problems here. let me explain what i am trying to do first. I have a page that has values that change on it, however i want to grab the values before they change, keep them, and then once a button is pushed, change the html to the original html. Now first of all my biggest problem is that when i try to uncomment the initial2 function, it just doesnt work. it brings me to the webpage then for some reason the html url tries to change and it says it can not find the page. the second, and more understandable problem for me, is that the function previousaccept i cant get to use the values from the previousnames function.
function previousnames()
{
name= document.getElementById('name').innerHTML;
imagetitle= document.getElementById('imagetitle').innerHTML;
location=document.getElementById('location').innerHTML;
similarities = document.getElementById('similarities').innerHTML;
type = document.getElementById('type').innerHTML;
cost = document.getElementById('cost').innerHTML;
date = document.getElementById('date').innerHTML;
pictureid = document.getElementById('pictureid').src;
}
function previousaccept(name,imagetitle,location,similarities,value,type,cost,date,pictureid)
{
document.getElementById('name').innerHTML = name;
document.getElementById('location').innerHTML = location;
document.getElementById('similarities').innerHTML = similarities;
document.getElementById('type').innerHTML = type;
document.getElementById('cost').innerHTML = cost;
document.getElementById('date').innerHTML = date;
window.alert(pictureid);
document.getElementById('pictureid').src = pictureid;
}
window.onload=initial();
function initial()
{
myvalues;
previousnames;
}
/*
function initial2()
{
myvalues;
previousnames();
}*/
If you set the location (which is window.location), then the browser will go to a new web page. That's what you're doing in the previousnames() function with this line:
location=document.getElementById('location').innerHTML;
If you're trying to have a global variable named location, then give it a different name that isn't already used by the browser.
Also, you should explicitly declare any global variables you intend to use outside of your functions rather than use implicitly declared variables like you are which makes your code very prone to errors.
I think this will do what you want. The key is to make sure that the scope of the variables you are trying to store is such that the functions have access to them all. I do this by defining an empty object dataStore at the start of the onload function, and also defining the 2 other functions within the onload function. Putting all the stored data in a single object is convenient and avoids naming problems (such as the window.location problem noted by the previous answer.)
window.onload = function() {
var dataStore = {};
function getInitialData() {
dataStore = {
name: document.getElementById('name').innerHTML,
imagetitle: document.getElementById('imagetitle').innerHTML,
// and so on...
}
}
function resetData() {
document.getElementById('name').innerHTML = dataStore.name;
document.getElementById('imagetitle').innerHTML = dataStore.imagetitle;
// and so on...
}
getInitialData();
//... then later when you want to reset all the values
resetData();
}​
How could I set the value of an item in a json object by passing in the name of it via a parameter to a function?
eg:
this.loadStates = function() {
that.setStateIfExists('inStock', true);
}
this.setStateIfExists = function (param, option) {
// i'd like this to be 'that.selectedFinderOptions.inStock = option'
that.selectedFinderOptions.param = option;
}
Is this even possible or should I be thinking of doing this differently?
Use an indexer:
that.selectedFinderOptions[param] = option;
Your use of the phrase "JSON object" has us a bit confused. JSON is a flattened, string representation of the serialization of one or more javascript objects. So, you don't do anything dynamically with a piece of JSON. It's just a string.
If, what you mean is that you have a javascript object instead, then we can discuss options. For a javascript object, you have a couple choices. First off, you can just use an attribute on that object and have it's value reflect what you want:
var myObj = {};
myObj.inStock = true;
Then, anyone can access myObj.inStock and get the current value of that property.
If what, you want is for the value of instock to be computed by a function rather than be static assigned to the object and you want your code to work across all browsers, then you would have to change the way you access that to be via a method call:
var myObj = {};
myObj.getInStockValue = function() {
// execute whatever code you want here to
// compute the desired value and return it when done
};
Then, anyone can access it with myObj.getInStockValue().
In your specific example, you could change this:
this.setStateIfExists = function (param, option) {
// i'd like this to be 'that.selectedFinderOptions.inStock = option'
that.selectedFinderOptions.param = option;
}
to this:
this.setStateIfExists = function (param, option) {
// i'd like this to be 'that.selectedFinderOptions.inStock = option'
that.selectedFinderOptions[param] = option;
}
When the parameter is dynamic and contained in a variable, you use the [param] syntax instead of the .param syntax. They both do the same thing logically, but the [param] syntax is the only one that works when the name of the thing you want to look up is in a variable.
i got a got a little embedded system that can be controlled via a webinterface.
the page looks like:
...
foo
...
is there a way to call this function just by http? like
http://<the-devices-ip>:80/javascipt:foo(bar) //wrong
thank you
You can do so by passing a querystring or a hash into the URL and execute a piece of JS which checks it during onload.
var query = window.location.search; // Gets '?foo=bar' from http://example.com/page.html?foo=bar
var hash = window.location.hash; // Gets '#foo' from http://example.com/page.html#foo
You only have to parse it further yourself or by using a 3rd party JS framework with plugin capabilities, like jQuery.
page1.html:
foo
page2.html:
<script type="text/javascript">
if(window.location.hash)
eval(window.location.hash)
</script>
I'm not saying it's a good idea. It might be helpful to document why you think you need to do this, there are probably better ways to accomplish whatever the actual goal is.
Note that doing this will not allow you to pass variables around. You need to have only static values in the javascript code executed on page2.html, or generate the href in page1.html dynamically.
Caveat: this will potentially open up your code to HTML and/or script injections. Filter rigorously.
I recently had to do something similar for a project that I was contracted out on. Like others, I used the hash portion of the URL to pass in JavaScript functions and parameters. However, the main difference was that I didn't do a simple eval of the entire string. I established a specific format to 1) narrow the amount of functions that could be executed, and 2) sanitize any input that the method required
The format, in full, is as follows:
http://somedomain.tld/path/?query=blah#specific.controller.object/method/['array', 'of', {json: 'arguments'}]
So, basically, you end up with the following string:
specific.controller.object/method/['array', 'of', {json: 'arguments'}]
I then wrote a parser to handle this string. Restrictions where exacted over what objects could be called by prepending with a sort of "namespace" object, in other words, calling it as part of a member of an existing, predetermined static object. For example, specific.controller.object, would be called as new com.project.specific.controller.object();. Here's something similar to my parser:
var data = location.hash.substr(1).split('/'),
controller = ("my.namespace." + data[0]).split("."),
// You can provide a default method if you want, my framework used `show`
method = data[1] || "show",
// must be an array for use with `apply`
params = data[2] || "[]";
// Parse the controller to find the appropriate object to instantiate.
// All objects are in reference to the global window object. Break
// them apart by their dot composition and step down through the object
// tree starting at window.
var composition = window;
for ( var i=0; i<controller.length; i++ ) {
composition = composition[ controller[i] ];
}
var obj = new composition;
// Handle the parameters. It may be the case that there "/" is present
// in the last argument. If so, add anything that was left out.
if ( data.length > 3 ) {
for ( var i=3; i<data.length; i++ ) {
params += '/' + data[i];
}
}
// Convert params from a string to an array.
// ***Possible injection point here***
params = dojo.fromJson(params);
// Make sure that the method runs in the proper context and
// pass it all of the parameters
obj[method].apply(obj, params);
Because the way the parser works, you required to provide parameters if none are needed, and in some cases, if you choose to allow default methods as I have, you don't have to specify which member on the object to call, which simplifies that construction of these URL's greatly.
Instead of using a static namespace object to restrict what objects could be instantiated, it would be trivial to use a white list of safe objects and methods.
foo represents the calling of a function, not the call to a url. There is no direct mapping between a url and a JavaScript function.