I was wondering how to refer to the long range of variables in the array.
I have fields called Check1, Check2, Check3 up to 60. I'd like to refer to the range of Check1-Check60.
//Do I have to mention ALL the 60 fields here?
var fieldsToValidate = ["Check1", "Check2", "Check3", "Check4", "Check5", "Check6", "Check7"];
Is there a cleaner/shorter way to write this?
edit:
Forgot to mention I am using JavaScript for Acrobat, here's the snippet:
//Do I have to mention ALL the 60 fields here?
var fieldsToValidate = ["Check1", "Check2", "Check3", "Check4", "Check5", "Check6", "Check7"]; //etc.
var emptyFields = [];
for (var i in fieldsToValidate) {
var f = this.getField(fieldsToValidate[i]);
if (f.valueAsString==f.defaultValue) {
emptyFields.push(f.name);
}
}
if (emptyFields.length>0) {
app.alert("Error! You must fill in all required Fields:\n" + emptyFields.join("\n"));
} else {
this.getField("Signature1").display = display.visible;
}
If all your field are simply like Check[n] where n is incremented by 1. You can do the following
var fieldsToValidate = []
for (let i = 1; i <= 60; i++) {
fieldsToValidate.push("Check" + i);
}
console.log(fieldsToValidate);
Using a generator:
console.log([...function*(n) {
for (let i = 0; i < n; i++) yield `Check${i + 1}`;
}(60)]);
This method works for me, Thank you!
var fieldsToValidate = []
for (let i = 1; i <= 60; i++) {
fieldsToValidate.push("Check" + i);
}
console.log(fieldsToValidate);
Related
I didn't find an answer to this, I need to concatenate two variables (ans & i) in Jquery to get ans1, ans2, etc. I tried this:
if(preguntaTipo<2){
var numero = "";
}
else{
var numero = $('#numero').val();
for (var i = 1; i < numero; i++) {
var ans.i = $('#ans'+i).val();
}
}
Its a mode to do like PHP $ans.$i? I also tried ans + i and it didn't work...
var ans.i = makes no sense.
You can't have periods/dots inside of variable names.
Is this what you're looking for?
var ans = [];
for (var i = 1; i < numero; i++) {
ans[i] = $('#ans' + i).val();
}
You could also use ans.push($('#ans' + i).val()); which would make the resulting answer array 0-based instead of 1-based.
I have encountered a very strange bug:
I derive a new array allSavings[] from another one (tours[]) and sort it in the function calculateAllSavings(). Before I call the function I can access tours[] just fine, but afterwards, I can't anymore. The div tags demo1 and demo2 both exist and are working fine for other outputs.
function euclDist(node1,node2){
if(node1 != node2){
var x = Math.pow(nodes[node2].x - nodes[node1].x,2);
var y = Math.pow(nodes[node2].y - nodes[node1].y,2);
var dist = Math.sqrt(x+y);
return dist;
}
else return 0.0;
}
function tourDist(members){
var tourDist = 0.0;
if (members.length>1){
for (i = 1; i < members.length; i++)
tourDist += euclDist(members[i],members[i-1]);
}
return tourDist;
}
function combineTours(tourA, tourB){
tourA.pop();
tourB.shift();
return tourA.concat(tourB);
}
function calculateSaving(tourA,tourB){
var costSeparate = tourDist(tourA) + tourDist(tourB);
var combTour = combineTours(tourA,tourB);
var costCombined = tourDist(combTour);
return costSeparate - costCombined;
}
function calculateAllSavings(){
var allPossibilities = [];
for(var i = 0; i < tours.length; i++){
for(var j = 0; j < tours.length; j++){
if(i != j)
var savingObj = {saving:calculateSaving(tours[i],tours[j]), tourA: i, tourB: j};
allPossibilities.push(savingObj);
}
}
allPossibilities.sort(function(a, b){
return b.saving-a.saving
})
document.getElementById("demo3").innerHTML = "success";
return allPossibilities;
}
//Initialize Array
var tours = [];
tours.push([0,1,2,3,0]);
tours.push([0,4,5,6,0]);
tours.push([0,7,8,0]);
tours.push([0,9,10,0]);
//BUG
document.getElementById("demo1").innerHTML = tours.join('\n'); // Shows array correctly
var allSavings = calculateAllSavings(); //BUG APPEARS HERE
document.getElementById("demo2").innerHTML = tours.join('\n'); // Doesn't show anything
Edit Solved:
combine() was overwriting the original tours[].
by doing the combining with cloned tours, the original was left untouchted.
function combineTours(tourA, tourB){
var tour1 = tourA.slice(0);
var tour2 = tourB.slice(0);
tour1.pop();
tour2.shift();
return tour1.concat(tour2);
}
Thanks to everyone who helped me
Well, in combineTours function you're calling .pop() method on one array and .shift() method on another, which removes one element from each of these arrays. In calculateAllSavings you're calling calculateSaving in a loop and it's calling combineTours, so you're effectively removing all elements from the sub-arrays.
Maybe you should just remove these lines from combineTours:
tourA.pop();
tourB.shift();
For the future: use console.log() for debugging, it could help you identify the issue.
Can you try this?
for(var i = 0; i < tours.length; i++){
for(var j = 0; j < tours[i].length; j++){
if(i != j)
var savingObj = {saving:calculateSaving(tours[i],tours[j]), tourA: i, tourB: j};
allPossibilities.push(savingObj);
}
}
Apart from this, you can also debug and see if your document.getElementById("demo2").innerHTML = tours.join('\n'); line actually gets executed. You may be running an infinite loop. Try and debug your code using chrome developer tools.
I would like to know if there is a way of creating a JavaScript object which is randomized. Understand randomized as such: the resulting object has a random set of properties, every of which has a random name. The problem boils down to two:
1) Is it possible to have an object created at runtime, without earlier specifying the amount of properties?
2) Is it possible to randomize names of the object's properties?
I'm looking for an explanation/solution, not only a no/yes answer.
A very crude way to do it, can't think of any use case for it:
function randomObject(){
var ret = {};
var propertyCount= Math.random() * 10;
for (var x = 0; x < propertyCount; x++ ){
ret[Math.random()] = Math.random();
}
return ret;
}
I don't see how it could be useful, but yes, it's possible.
var MAX_PROPERTIES = 50;
var ALLOWED_CHARACTERS_IN_KEY = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
var MAX_KEY_LENGTH = 30;
var object = {};
var propertiesCount = Math.round(Math.random() * MAX_PROPERTIES);
for(var i = 0 ; i < propertiesCount ; i++) {
var keyLength = Math.round(Math.random() * MAX_KEY_LENGTH);
var randKey = "";
for(var j = 0 ; j < keyLength ; j++) {
randKey += ALLOWED_CHARACTERS_IN_KEY[Math.floor(Math.random() * ALLOWED_CHARACTERS_IN_KEY.length)];
}
var randValue = Math.random();
object[randKey] = randValue;
}
Note that some keys could begin with a number, which is not callable with the dot notation.
Example :
{
"NmkQZWeW9_ojadERwK74HXYj43Lw":0.3039316821878978,
"PZiFauEC6H":0.04273172815465165,
"2m7cMrwRPoxpa8LvmpAaJ":0.7010494474513925,
"D":0.4552683870622114,
"HQhIxPxO8tsdocRuGJpnhB7k2PjD":0.18360190519964337,
"rVwM8":0.8681098855694265,
"3Vf5HGYDOmUli3":0.527829742115212,
"fQ4ryGL2cxhJeRd":0.10353706566292953,
"D_DQqODu_":0.1272988336424956,
"8UY0a7":0.17057184875868092,
"8i1uVtPwzl0KRA8iYZ4uKcPKF":0.9554370948377217,
"TTi":0.038665872114993616,
"YofUj9RrK7foQrl":0.5835241172217945,
"sb3SzEB_":0.17136910050721899,
"801FopHCCML4ozrfmjak":0.10999126507324442,
"D8":0.05981337403919851,
"oL8ZZvrAG":0.36816486041399255,
"hfXxJ0sNp42y2HYEDXLBYgZ6mV":0.13977757384990708,
"2xx4AJrQswA5TIcXr":0.8610074761855161,
"68RNcKQmgnh_qTG":0.5234909406332302,
"wJsV8BRo1cT2MtXDuh":0.4497261910215308,
"6yFr4E81bvXK":0.5996413679577888,
"Px2bjBvFSBu":0.017922504534248707,
"yazK1KQbmUhE4Ul1rZX5hf0yulX_JK":0.7105144243046027,
"cXmdnvmP":0.028121925940253756,
"R_fDjw9yBejk3":0.699514797889162,
"z":0.34347612922580006,
"2kTX6Q2tzbCo3":0.678962211994213
}
(forgive me if I use slightly incorrect language - feel free to constructively correct as needed)
There are a couple posts about getting data from JSON data of siblings in the returned object, but I'm having trouble applying that information to my situation:
I have a bunch of objects that are getting returned as JSON from a REST call and for each object with a node of a certain key:value I need to extract the numeric value of a sibling node of a specific key. For example:
For the following list of objects, I need to add up the numbers in "file_size" for each object with matching "desc" and return that to matching input values on the page.
{"ResultSet":{
Result":[
{
"file_size":"722694",
"desc":"description1",
"format":"GIF"
},
{
"file_size":"19754932",
"desc":"description1",
"format":"JPEG"
},
{
"file_size":"778174",
"desc":"description2",
"format":"GIF"
},
{
"file_size":"244569996",
"desc":"description1",
"format":"PNG"
},
{
"file_size":"466918",
"desc":"description2",
"format":"TIFF"
}
]
}}
You can use the following function:
function findSum(description, array) {
var i = 0;
var sum = 0;
for(i = 0; i < array.length; i++) {
if(array[i]["desc"] == description && array[i].hasOwnProperty("file_size")) {
sum += parseInt(array[i]["file_size"], 10);
}
}
alert(sum);
}
And call it like this:
findSum("description1", ResultSet.Result);
To display an alert with the summation of all "description1" file sizes.
A working JSFiddle is here: http://jsfiddle.net/Q9n2U/.
In response to your updates and comments, here is some new code that creates some divs with the summations for all descriptions. I took out the hasOwnProperty code because you changed your data set, but note that if you have objects in the data array without the file_size property, you must use hasOwnProperty to check for it. You should be able to adjust this for your jQuery .each fairly easily.
var data = {};
var array = ResultSet.Result;
var i = 0;
var currentDesc, currentSize;
var sizeDiv;
var sumItem;
//Sum the sizes for each description
for(i = 0; i < array.length; i++) {
currentDesc = array[i]["desc"];
currentSize = parseInt(array[i]["file_size"], 10);
data[currentDesc] =
typeof data[currentDesc] === "undefined"
? currentSize
: data[currentDesc] + currentSize;
}
//Print the summations to divs on the page
for(sumItem in data) {
if(data.hasOwnProperty(sumItem)) {
sizeDiv = document.createElement("div");
sizeDiv.innerHTML = sumItem + ": " + data[sumItem].toString();
document.body.appendChild(sizeDiv);
}
}
A working JSFiddle is here: http://jsfiddle.net/DxCLu/.
That's an array embedded in an object, so
data.ResultSet.Result[2].file_size
would give you 778174
var sum = {}, result = ResultSet.Result
// Initialize Sum Storage
for(var i = 0; i < result.length; i++) {
sum[result[i].desc] = 0;
}
// Sum the matching file size
for(var i = 0; i < result.length; i++) {
sum[result[i].desc] += parseInt(result[i]["file_size"]
}
After executing above code, you will have a JSON named sum like this
sum = {
"description1": 20477629,
"description2": 1246092
};
An iterate like below should do the job,
var result = data.ResultSet.Result;
var stat = {};
for (var i = 0; i < result.length; i++) {
if (stat.hasOwnProperty(result[i].cat_desc)) {
if (result[i].hasOwnProperty('file_size')) {
stat[result[i].cat_desc] += parseInt(result[i].file_size, 10);
}
} else {
stat[result[i].cat_desc] = parseInt(result[i].file_size, 10);
}
}
DEMO: http://jsfiddle.net/HtrLu/1/
I'm trying to list all three letter permutations and this is the code I have -
window.permute = function(){
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var searchTerm ="aaa";
var position = 2;
changeString(searchTerm, position);
}
window.changeString = function(searchTerm, position){
if (position <0){
alert(newString);
return;
}
var alphabet = "abcdefghijklmnopqrstuvwxyz"
for (j=0; j < 26;j++){
var newString = searchTerm.substr(0, position) + alphabet[j] + searchTerm.substr(position+1);
var newPosition = position -1;
changeString(newString,newPosition);
}
return;
}
It's not working and I'm not sure why- can anyone help?
var permutate = (function() {
var results = [];
function doPermute(input, output, used, size, level) {
if (size == level) {
var word = output.join('');
results.push(word);
return;
}
level++;
for (var i = 0; i < input.length; i++) {
if (used[i]) {
continue;
}
used[i] = true;
output.push(input[i]);
doPermute(input, output, used, size, level);
used[i] = false;
output.pop();
}
}
return {
getPermutations: function(input, size) {
var chars = input.split('');
var output = [];
var used = new Array(chars.length);
doPermute(chars, output, used, size, 0);
return results;
}
}
})();
for more information, visit http://jinwolf.tumblr.com/post/26476479113/draw-something-cheat
for an working example, check this jsfiddle http://jsfiddle.net/jinwolf/Ek4N5/31/
alert(newString);
newString is not defined right there. Instead, you should use the argument passed:
alert(searchTerm);
Edit: I'm not entirely sure of your approach. It seems overly complicated. This seems to work. I understand that you rather have your own code working, but perhaps this helps you in solving. I don't quite get your substr part.
http://jsfiddle.net/NUG2A/2/
var alphabet = "abc"; // shortened to save time
function permute(text) {
if(text.length === 3) { // if length is 3, combination is valid; alert
console.log(text); // or alert
} else {
var newalphabet = alphabet.split("").filter(function(v) {
return text.indexOf(v) === -1;
}); // construct a new alphabet of characters that are not used yet
// because each letter may only occur once in each combination
for(var i = 0; i < newalphabet.length; i++) {
permute(text + newalphabet[i]); // call permute with current text + new
// letter from filtered alphabet
}
}
}
permute("");
This will result in the following being called:
permute("");
permute("a");
permute("ab");
permute("abc"); // alert
permute("ac");
permute("acb"); // alert
permute("b");
// ...
I'm not sure from your question that you mean "permutations" because usually permutations do not include repeated elements where it looks like you want to include "aaa".
Here are several algorithms for listing permutations you can go check out. If it turns out you mean to have repetitions, it looks like pimvdb has you covered.
Edit: So you know what you are getting into run-time wise:
With repetition (aaa,aab,...): n^k = 26^3 = 17,576
Without repetition (abc,bac,...): n!/(n-k)! = 26!/(26-3)! = 15,600
for (j=0; j < 26;j++){
should be
for (var j=0; j<26; j++) {
Without the declaration, j is a global variable, so it only takes one iteration to get to 26 and then all the loops terminate.
For permutations a recursive algorith as pimvd showed is always nice but don't forget you can just brute force it with for-loops when N is small:
for(int x1=0; x1 < 26; x1++)
for(int x2=0; x2 < 26; x2++)
for(int x3=0; x3 < 26; x3++){
//do something with x1, x2, x3
}
In C#:
void DoPermuation(string s)
{
var pool = new HashSet<string>();
//Permute("", , pool);
pool = Permute(new List<char>(s));
int i = 0;
foreach (var item in pool) Console.WriteLine("{0:D2}: {1}", ++i, item);
}
HashSet<string> Permute(List<char> range)
{
if (range.Count == 1) return new HashSet<string>(new string[] { range[0].ToString() });
var pool = new HashSet<string>();
foreach (var c in range)
{
var list = new List<char>(range);
list.Remove(c);
foreach (var item in Permute(list)) pool.Add(c + item);
}
return pool;
}