This is the code that I currently have, one problem that is happening is I cannot use test() because presets[index].name and value are not visible outside of their function scope, how should I declare my array of objects in the global scope in order for me to be able to access these two variables in other functions?
var presets = [];
var index;
function CreatePresetArray(AMib, AVar) {
var parentpresetStringOID = snmp.getOID(AMib, AVar);
var presetStringOID = parentpresetStringOID;
parentpresetStringOID = parentpresetStringOID.substring(0, parentpresetStringOID.length - 2);
log.error("parentpresetStringOID is " + parentpresetStringOID);
var presetswitches = {};
for (var i = 1; i < 41; i++) {
presets.push(presetswitches);
try {
log.error("presetStringOID before getNextVB= " + presetStringOID);
vb = snmp.getNextVB(presetStringOID);
presetStringOID = vb.oid;
log.error("presetStringOID after getnextVB= " + presetStringOID);
var presetStringVal = snmp.get(presetStringOID);
log.error("presetStringVal= " + presetStringVal);
index = i - 1;
presets[index].name = presetStringOID;
presets[index].value = presetStringVal;
log.error("preset array's OID at position [" + index + "] is" + presets[index].name + " and the value stored is " + presets[index].value);
//log.error("presets Array value ["+index+"] = "+presets[index].configs);
if (presetStringOID.indexOf(parentpresetStringOID) != 0) {
break;
}
} catch (ie) {
log.error("couldn't load preset array " + index);
};
};
}
CreatePresetArray(presetMib, "presetString");
function test() {
for (i = 1; i < 41; i++) {
log.error("test" + presets[index].name + " " + presets[index].value);
};
}
test();
The for loop in your function test iterates over i but uses index inside the loop. Perhaps you meant to use
for (i = 0; i < 40; i++) { // 1 lower as you were using `index = i - 1` before
log.error("test" + presets[i].name + " " + presets[i].value);
}
Re-wrote your code. I don't think I made that much by way of change. If this doesn't clear up your problem, consider: Is the catch happening each iteration? Is the problem actually coming from a different method which is only visible here? Also, consider logging the whole presets Array when debugging to see what it looks like.
var presets = [];
function CreatePresetArray(AMib, AVar) {
var parentPresetOID, presetOID, presetValue, preset, vb, i;
parentPresetOID = snmp.getOID(AMib, AVar);
presetOID = parentPresetOID; // initial
parentPresetOID = parentPresetOID.substring(0, parentPresetOID.length - 2);
log.error("parentPresetOID is " + parentPresetOID);
presets = []; // empty array in case not already empty
for (i = 0; i < 40; ++i) {
try {
preset = {}; // new object
// new presetOID
vb = snmp.getNextVB(presetOID);
presetOID = vb.oid;
log.error("presetOID after getnextVB= " + presetOID);
// new value
presetValue = snmp.get(presetOID);
log.error("presetValue= " + presetValue);
// append data to object
preset.name = presetOID;
preset.value = presetValue;
// append object to array
presets.push(preset);
// more logging
log.error(
"preset array's OID at position [" + i + "]" +
" is" + presets[i].name + " and " +
"the value stored is " + presets[i].value
);
if (presetOID.indexOf(parentPresetOID) !== 0) {
break;
}
} catch (ie) {
log.error("couldn't load preset array " + i);
if (presets.length !== i + 1) { // enter dummy for failed item
presets.push(null);
}
}
}
}
Two options come to mind immediately:
you could pass the preset array as a argument to test().
You could put both CreatePresetArray() and test() inside a wrapper function and declare preset array at the top of your wrapper. That would give them both access to the variable.
It's generally considered Bad Form to declare globals if it can be avoided. Pollutes the namespace.
Related
So, I wanted to automate some of my coding process. I figured maybe I don't have to manually name all the constants that refer to classes, and have a function do that. Here's my code, which, I feel, should work. Of course it doesn't. Should it? If not, why not?
function definitions() {
var allElem = document.querySelectorAll("*"); //Get every HTML element.
for(a = 0; a < allElem.length; a++) { //Iterate through every HTML element.
if (allElem[a].classList.length == 0) { //If an element has no class...
console.log("no var declared, " + a); //...ignore it.
} else { //If it has one or more classes...
for(b = 0; b < allElem[a].classList.length; b++) { //...iterate through the classList.
eval("const " + allElem[a].classList[b] + " = " + "document.getElementsByClassName('" + allElem[a].classList[b] + "');"); //Declare a constant named for the class if refers to
console.log("const " + allElem[a].classList[b] + " = " + "document.getElementsByClassName('" + allElem[a].classList[b] + "');");
}
}
}
console.log(document.getElementsByClassName('clone').length); //This logs 10, which is correct.
console.log(clone.length); // 'Uncaught ReferenceError: clone is not defined'. But... but... I thought I did... :'(
}
For my chrome extension, I have a function called storeGroup that returns an object. However, in function storeTabsInfo, when I call storeGroup and set it equal to another object, the parts inside the object are undefined. The object is being populated correctly in storeGroup, so I'm not sure why it's undefined?
function storeTabsInfo(promptUser, group)
{
var tabGroup = {};
chrome.windows.getCurrent(function(currentWindow)
{
chrome.tabs.getAllInWindow(currentWindow.id, function(tabs)
{
/* gets each tab's name and url from an array of tabs and stores them into arrays*/
var tabName = [];
var tabUrl = [];
var tabCount = 0;
for (; tabCount < tabs.length; tabCount++)
{
tabName[tabCount] = tabs[tabCount].title;
tabUrl[tabCount] = tabs[tabCount].url;
}
tabGroup = storeGroup(promptUser, group, tabName, tabUrl, tabCount); // tabGroup does not store object correctly
console.log("tabGroup: " + tabGroup.tabName); // UNDEFINED
chrome.storage.local.set(tabGroup);
})
})
}
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
var groupCountValue = group.groupCount;
var groupName = "groupName" + groupCountValue;
groupObject[groupName] = promptUser;
var tabName = "tabName" + groupCountValue;
groupObject[tabName] = name;
var tabUrl = "tabUrl" + groupCountValue;
groupObject[tabUrl] = url;
var tabCount = "tabCount" + groupCountValue;
groupObject[tabCount] = count;
var groupCount = "groupCount" + groupCountValue;
groupObject[groupCount] = groupCountValue + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject[groupName] + " " + groupObject[tabName] + " " + groupObject[tabUrl] + " " + groupObject[tabCount] + " " + groupObject[groupCount]);
return groupObject;
}
As i said in the comment above you created the groupObject dict keys with the group count so you should use it again to access them or remove it, if you want to use it again although i think this isnt necessary so use:-
... ,tabGroup[tabName + group.groupCount]...
But if you want to get it easily as you wrote just write this code instead of your code:-
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
groupObject['groupName'] = promptUser;
groupObject['tabName'] = name;
groupObject['tabUrl'] = url;
groupObject['tabCount'] = count;
groupObject['groupCount'] = group.groupCount + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject['groupName'] +
" " + groupObject['tabName'] + " " + groupObject['tabUrl'] +
" " + groupObject['tabCount'] + " " +
groupObject['groupCount']);
return groupObject;
}
I'm having trouble producing a script to match an object's value in object array based on an object's value in a separate array, and retrieve a separate value from that object.
I have used standard for-loops and the current iteration in jQuery each.
I have also tried setting the if statement to look for the two values as ==, but it always produces non matches (or -1).
Can anyone steer me in the right direction here?
transfers = [
{Package: "1", Origin_Facility = "a"},
{Package: "2", Origin_Facility = "b"}
];
storeData = [
{fromPackage: "1,6,26"}
]
var storeDataEach = function( sx, sxv ) {
var transfersEach = function( sy, syv ) {
if(storeData[sx].fromPackage.indexOf(transfers[sy].Package) > -1){
var facilityStore = transfers[sx].Origin_Facility;
storeData[sx].origin = facilityStore + " + " + transfers[sy].Package + ' + ' + storeData[sx].fromPackage;
return false;
} else {storeData[sx].origin = 'error' + transfers[sy].Package + " + " + storeData[sx].fromPackage;return false;}
};
jQuery.each(transfers, transfersEach);
}
jQuery.each(storeData, storeDataEach);
The main problem is you are returning false from the $.each loop which will stop the iteration
A crude fix is to remove the return from else block
var storeDataEach = function(sx, sxv) {
var transfersEach = function(sy, syv) {
if (storeData[sx].fromPackage.indexOf(transfers[sy].Package) > -1) {
var facilityStore = transfers[sx].Origin_Facility;
storeData[sx].origin = facilityStore + " + " + transfers[sy].Package + ' + ' + storeData[sx].fromPackage;
return false;
} else {
storeData[sx].origin = 'error' + transfers[sy].Package + " + " + storeData[sx].fromPackage;
}
};
jQuery.each(transfers, transfersEach);
}
But this still have problems with the data structure, in your example you have 26 in the fromPackage, now if you have a package value of 2 that also will return a positive result
I have trouble accessing object' property in the example below. On the third line I'd like to have the number 42 replaced with the value of the variable devNumTemp, but so far I'm not successfull.
What is the proper way to do this? I've tried several options, but never getting any further than getting undefined.
function getTempDev(devNumTemp, devNumHum, id, description){
$.getJSON("http://someurl.com/DeviceNum=" + devNumTemp,function(result){
var array = result.Device_Num_42.states;
function objectFindByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
$("#id").html(description + "<div class='right'>" + array[i].value + "°C" + " (" + someVariable + "%" + ")" + "<br></div>");
}
}
};
objectFindByKey(array, 'service', 'something');
});
};
You can acces to object's properties like this
var array = result["Device_Num_" + devNumTemp].states;
It's considered a good practice to test for field's existance before trying to access it:
var array = [];
if (result && result["Device_Num_" + devNumTemp]){
array = result["Device_Num_" + devNumTemp].states;
}
This way we prevent Null Pointer Exception type errors.
I've been working on a script which collates the scores for a list of user from a website. One problem is though, I'm trying to load the next page in the while loop, but the function is not being loaded...
casper.then(function () {
var fs = require('fs');
json = require('usernames.json');
var length = json.username.length;
leaderboard = {};
for (var ii = 0; ii < length; ii++) {
var currentName = json.username[ii];
this.thenOpen("http://www.url.com?ul=" + currentName + "&sortdir=desc&sort=lastfound", function (id) {
return function () {
this.capture("Screenshots/" + json.username[id] + ".png");
if (!casper.exists(x("//*[contains(text(), 'That username does not exist in the system')]"))) {
if (casper.exists(x('//*[#id="ctl00_ContentBody_ResultsPanel"]/table[2]'))) {
this.thenEvaluate(tgsagc.tagNextLink);
tgsagc.cacheCount = 0;
tgsagc.
continue = true;
this.echo("------------ " + json.username[id] + " ------------");
while (tgsagc.
continue) {
this.then(function () {
this.evaluate(tgsagc.tagNextLink);
var findDates, pageNumber;
pageNumber = this.evaluate(tgsagc.pageNumber);
findDates = this.evaluate(tgsagc.getFindDates);
this.echo("Found " + findDates.length + " on page " + pageNumber);
tgsagc.checkFinds(findDates);
this.echo(tgsagc.cacheCount + " Caches for " + json.username[id]);
this.echo("Continue? " + tgsagc["continue"]);
this.click("#tgsagc-link-next");
});
}
leaderboard[json.username[id]] = tgsagc.cacheCount;
console.log("Final Count: " + leaderboard[json.username[id]]);
console.log(JSON.stringify(leaderboard));
} else {
this.echo("------------ " + json.username[id] + " ------------");
this.echo("0 Caches Found");
leaderboard[json.username[id]] = 0;
console.log(JSON.stringify(leaderboard));
}
} else {
this.echo("------------ " + json.username[id] + " ------------");
this.echo("No User found with that Username");
leaderboard[json.username[id]] = null;
console.log(JSON.stringify(leaderboard));
}
});
while (tgsagc.continue) {
this.then(function(){
this.evaluate(tgsagc.tagNextLink);
var findDates, pageNumber;
pageNumber = this.evaluate(tgsagc.pageNumber);
findDates = this.evaluate(tgsagc.getFindDates);
this.echo("Found " + findDates.length + " on page " + pageNumber);
tgsagc.checkFinds(findDates);
this.echo(tgsagc.cacheCount + " Caches for " + json.username[id]);
this.echo("Continue? " + tgsagc["continue"]);
return this.click("#tgsagc-link-next");
});
}
Ok, looking at this code I can suggest a couple of changes you should make:
I don't think you should be calling return from within your function within then(). This maybe terminating the function prematurely. Looking at the casperjs documentation, the examples don't return anything either.
Within your while loop, what sets "tgsagc.continue" to false?
Don't use "continue" as a variable name. It is a reserved word in Javascript used for terminating an iteration of a loop. In your case this shouldn't be a problem, but its bad practice anyhow.
Don't continually re-define the method within your call to the then() function. Refactor your code so that it is defined once elsewhere.
We ended up having to scope the function, so it loads the next page in the loop.
This is mainly because CasperJS is not designed to calculate scores, and it tries to asynchronously do the calculation, missing the required functions