FOR loop and Array issue - javascript

I'm using Adobe Livecycle Designer ES4 to create some report. Based on XML a try to fill table. I have problem with Array. I push data into array in for loop. Below examples of my code:
Results - blank textbox
var print_data = xfa.record.containerPrintingData;
var sfcArray = [];
for (var i = 0; i < 10; i++) {
sfc = print_data.resolveNode("sfcPrintingData["+ i +"]").sfc.value;
sfcArray.push(sfc);
};
this.rawValue = sfcArray.toString();
Results - get all items
var print_data = xfa.record.containerPrintingData;
var sfcArray = [];
for (var i = 0; i < 10; i++) {
sfc = print_data.resolveNode("sfcPrintingData["+ i +"]").sfc.value;
sfcArray.push(sfc);
this.rawValue = sfcArray.toString();
}
Results - get 2nd item x 10
var print_data = xfa.record.containerPrintingData;
var sfcArray = [];
for (var i = 0; i < 10; i++) {
sfc = print_data.resolveNode("sfcPrintingData[1]").sfc.value;
sfcArray.push(sfc);
this.rawValue = sfcArray.toString();
}
Why 1st example don't work and 2nd work correct? I need use this array in another loops. How to solve it?

Because, If it has 2 items, and you looping it for 10.
What happends is, when this.rawValue = sfcArray.toString(); is inside the loop, this.rawValue gets updated 2 times. First time One item will be there. second time 2 items.
For the next iteration there is no 3rd item. So code breaks with error. But this.rawValue still have 2 items.
Where as, when this.rawValue = sfcArray.toString(); is outside the loop, the code breaks with error and this.rawValue don't have any items in it.

Related

Getting the same array using Math.random every time. How to generate different array without refreshing the browser?

I am trying to make a sorting visualizer. But when I am creating a array using following code, every time when I create a new array I am getting the same array as previous one! I have to refresh the page to get a new array. What will I have to do in order to get different array without refreshing through browser.
let sortingMethod = "";
let array = [];
function between(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function createArray() {
for(let i = 0; i < 20; i++) {
array.push(between(20));
}
let arena = document.querySelector(".arena");
arena.innerHTML = '';
for(let i = 0; i < 20; i++) {
let element = document.createElement('div');
element.setAttribute('class', 'element');
console.log(array[i]);
element.style.height = (array[i] * 20) + "px";
arena.appendChild(element);
}
//console.log("created");
}
let create = document.getElementById("create");
create.addEventListener('click', createArray);
You are never clearing your array. So, each time you call createArray, new values are just appended to the end of the already filled array, but you only use first 20 values each time.
To solve your problem, just write this part of code let array = []; inside your createArray function.

Multiple loops in apps script

I am trying to run a replace text function on my slides based on an two arrays; the first array is the values that are to be replaced and the second array are the values that the corresponding values in the first array should be replaced with.
I.e. the first value in the first array should be replaced by the first value in the second array.
This is my attempt at doing it
function myFunction() {
var currentPresentationSlide = SlidesApp.getActivePresentation().getSlides();
var array1 = ['{{remove}}','{{remove2}}','{{remove3}}'];
var array2 = ['new value','new value2','new value 3'];
for (i = 0, s = 0, x = 0; i < currentPresentationSlide.length, s < array1.length, x < array2.length; i++, s++, x++) {
currentPresentationSlide[i].replaceAllText(array1[s],array2[x])
}
}
What further complicates it is, that the replaceAllText will only run on a single page and not the entire presentation, hence it will have to be run as a loop on each individual page in the slide (which is the reason for the loop with the i variable.
Does anyone know what I am doing wrong, cause this is not working for me
Thanks to Rup in the comments i solved it. Just in case anyone has the same issue this is my solution:
function myFunction() {
var currentPresentationSlide = SlidesApp.getActivePresentation().getSlides();
var array1 = ['{{remove}}','{{remove2}}','{{remove3}}'];
var array2 = ['new value','new value 2','new value 3'];
for (i = 0; i < currentPresentationSlide.length; i++) {
for (s = 0; s < array1.length; s++)
currentPresentationSlide[i].replaceAllText(array1[s],array2[s])
}
}

Why is my JavaScript array showing a two element count when there is supposed to be only one?

I have an JS Array that is supposed to show only one element. It does, however its index is 1 rather than 0 and the count is 2. Also the array does not show a 0 index.
My code:
var _UnitOfMeasureRelatedUnitData = [];
var rows = $('#jqxUOMRelatedUnitsDropdownGrid').jqxGrid('getrows');
var RecordCount = 0;
if (rows.length !== 1 && rows[0]["UOMRelatedUnit_Name"] !== ""){
for(var i = 0; i < rows.length; i++){
var row = rows[i];
var _row = {};
if(row.UOMRelatedUnit_AddItem !== F) {
RecordCount += 1;
_row["Name"] = $("#txtUnitOfMeasureSetName").val();
_row["Active"] = T;
_row["UnitOfMeasureTypeID"] = $("input[type='radio'][id='rblUnitOfMeasureType']:checked").val();
_row["BaseUnitID"] = $("input[type='radio'][id='rblUnitOfMeasureBaseUnit']:checked").val();
_row["RelatedUnitDisplayOrder"] = RecordCount;
_row["RelatedUnitName"] = row.UOMRelatedUnit_Name;
_row["RelatedUnitAbbreviation"] = row.UOMRelatedUnit_Abbreviation;
_row["RelatedUnitConversionRatio"] = row.UOMRelatedUnit_ConversionOfBaseUnits;
_row["UnitOfMeasureSetID"] = UnitOfMeasureSetID;
_UnitOfMeasureRelatedUnitData[i] = _row;
}
}
....
}
In my JQx Grid, I have at least four choices. For this issue, Ive only selected the 2 choice in the Grid and its AddItem value is True, everything else is False.
What do I need to change in my logic as I can not see it at this point?
EDIT 1
I overlooked the placement of RecordCount += 1;, I will try moving it to the end of the assignments and see what happens.
EDIT 2
The placement made no difference.
Maintain another variable for indexing your data like this
var index=0; // place this outside of for loop
_UnitOfMeasureRelatedUnitData[index++] = _row;
you don't need RecordCount += 1; .
you can get the rowscount by using _UnitOfMeasureRelatedUnitData.length

ParseFloat array values

I'm trying to parse the values in my array then add them to a chart. Problem is I'm getting some unexpected numbers on the out put. I loop through and populate my array. On the button click I loop through and parse the data and put it into another array to pass to a chart series. This in theory works but the data points received are in accurate. I've attached a picture of what the console out puts look like. Once I parse it either i'm getting the first digit of the element or half of the number.
Thank you
Here is the code :
var testData = [];
for (var i = 0; i < 5; i++) {
testData[i] = populationData[i].Census;
console.log(testData[i]);
}
// the button action
$('#button').click(function () {
var mySeries = [];
var data = [];
for (var i = 0; i < 5; i++) {
data[i] = parseFloat(testData[i]);
mySeries[i] = data[i];
}
console.log(mySeries);
var chart = $('#container').highcharts();
chart.series[0].setData(mySeries);
You need to remove the commas - JavaScript does not use thousand separators
parseFloat(testData[i].replace(/,/g,""));
or just
parseInt(testData[i].replace(/,/g,""),10);
if there are no decimals

javascript - array does not get set back to [] (blank)

I have this code and every time that the first for loop starts again I want it to reset the array to blank as it is using a new user, but I get an out put with all the values in one array.
var items = [];
for (var i = 0; i < userArray.length; i++) {
items.length = 0;
for (var i2 = 0; i2 < test.length; i2++) {
var UserFavourite = Parse.Object.extend("UserFavourite");
var queryUserFav = new Parse.Query(UserFavourite);
queryUserFav.equalTo('item', test[i2].get('item'));
queryUserFav.equalTo('school', test[i2].get('school'));
queryUserFav.equalTo('user1', userArray[i])
queryUserFav.find().then(function(res) {
for (var i3 = 0; i3 < res.length; i3++){
var item = res[i3];
var itemName = item.get('item');
items.push(itemName);
if (items !== []) {
console.log(items.toString()+" + ")
}
}
});
}
}
userArray.length is equal to 2 and test.length is equal to 20. If you were wondering. And when it get to the first for loop I want the array to be set back to blank but it isn't?
Thanks for the help in advance.
I thnk you should use set this:
items.length = 0
because items = []
creates a new array which is not the same.
Also add some promises to make the async requests wait
Have you tried:
items.length = 0;
instead of:
items = [];
Can you please concatenate a "+" to the items variable in console log, like so:
console.log(items.toString()+" + ");
Just for debugging purposes to see if the array is actually being cleared or not. I believe it already might be cleared.
Your issue is that you're executing a loop and triggering async code.
Your loop will completely finish before the first bit of async code is executed:
i == 0
reset items
loop over test (20 items)
queue up a find() with async success handler
i == 1
reset items
loop over test (20 items)
queue up a find() with async success handler
... some time later when find() calls finish ...
call each async block using the items array
Unless there's some other code you're not showing that needs to access the items array, just create it inside your success handler instead:
queryUserFav.find().then(function(res) {
// create array here:
var items = [];
for (var i3 = 0; i3 < res.length; i3++){
var item = res[i3];
var itemName = item.get('item');
items.push(itemName);
if (items !== []) {
console.log(items.toString()+" + ")
}
}
});

Categories