initialize variable repeatedly using for loop in javascript - javascript

my question is can i possibly initialize variables repeatedly (with changing only numbers after them) this is my code
for(i = truStorage.getItem('elementCount'); i>0; i--) {
var obj = truStorage.getItem("element_" + i);
var [obj_+i] = element(erd.Entity , obj.posx, obj.posy, obj.text );}
};
basically i just want to initialize a variable like
something_i = "";
and the result will be like this
var element_1 = element(erd.Entity, 100, 200, "Employee");
var element_2 = element(erd.Entity, 100, 400, "Salesman");
var element_3 = element(erd.WeakEntity, 530, 200, "Wage");
var element_4 = element(erd.IdentifyingRelationship, 350, 190, "gets paid");
im not trying to use variables as a storage but rather to instantiate an element for a function.

This is a job for an array.
var something = [];
var somethings = 5;
for(var i = 0; i < somethings; i++) {
something[i] = "";
}
You should now be able to access the five values like this:
console.log(something[0])
console.log(something[1])
console.log(something[2])
console.log(something[3])
console.log(something[4])
Notice you use 0 to access the first element. That's just how it is because JavaScript arrays are zero-based.

This is best scenario to use array:
var counter=0,something = new Array();
for(i = truStorage.getItem('elementCount'); i>0; i--) {
something[counter] = truStorage.getItem("element_" + i).text;
counter++;
}
};

Try:
for(var i=1; i<=4; i++) {
this["something_" + i] = i;
}
console.log(something_1); //outputs 1;
console.log(something_2); //outputs 2;
console.log(something_3); //outputs 3;
console.log(something_4); //outputs 4;
Note: using an array will be faster!

Related

How to loop over an array of objects using javascript?

I'm trying to loop an array that contains objects and I keep getting and error: "Cannot set property 'color' of undefined". What am I doing wrong?
var ObjectTest = function(something1, something2){
this.Name = something1;
this.Job = something2;
this.color = '';
this.numbers = [];
}
var first = new ObjectTest('Paul', 'teacher');
var second = new ObjectTest('Jane', 'doctor');
var third = new ObjectTest('Mike', 'student');
var someArray = [];
someArray.push(first, second, third);
console.log(someArray);
for(var i =0; i <= someArray.length; i++){
someArray[i].color = 'red';
};
You need to iterate until the length of the array but not over, because indices are zero based
for (var i = 0; i < someArray.length; i++) {
// ^
An array returns undefined for a not existing item. undefined has no property to assign a new value.
var ObjectTest = function(something1, something2) {
this.Name = something1;
this.Job = something2;
this.color = '';
this.numbers = [];
};
var first = new ObjectTest('Paul', 'teacher');
var second = new ObjectTest('Jane', 'doctor');
var third = new ObjectTest('Mike', 'student');
var someArray = [];
someArray.push(first, second, third);
for (var i = 0; i < someArray.length; i++) {
someArray[i].color = 'red';
} // no semicolon here
console.log(someArray);
<= was rong
var ObjectTest = function(something1, something2){
this.Name = something1;
this.Job = something2;
this.color = '';
this.numbers = [];
}
var first = new ObjectTest('Paul', 'teacher');
var second = new ObjectTest('Jane', 'doctor');
var third = new ObjectTest('Mike', 'student');
var someArray = [];
someArray.push(first, second, third);
for(var i =0; i < someArray.length; i++){
someArray[i].color = 'red';
};
console.log(someArray);
Replace <= to < in your loop.
There's only 3 items on the array, meaning you have indexes 0, 1 and 2. The loop should stop when it arrives at at 3. But since you used <= and not <, i <= 3 when i is 3 is true thus executing the code. The error is caused by someArray[3] not existing.
A safer way to loop through arrays without dealing with indexes is to use array.forEach. It only loops as many times as there are items in the array.
someArray.forEach((object, index) => {
object.color = 'red'
})
An easier way to go over an array is to use the forEach.
Something like this:
someArray.forEach(data => data.color = 'red');

Google Apps Script: Comparing Arrays for Unique Values

I'm working from the solution provided HERE to compare two arrays. The example provided returns values found in both arrays to Array1 (same) and values only found on one or the other two Array2 (diff).
ISSUE: When I apply it to my own script, valuesDATA returns nothing and valuesCheckSeeding returns ALL values from both arrays
DESIRED RESULT: I have two arrays that I'd either like to create a third out of, or only select values from the first array, valuesDATA which are NOT present in the second, valuesCheckSeeding. Using the solution above, I was trying to have all values not found in valuesCheckSeeding AND valuesDATA pushed to valuesDATA.
SAMPLE OF valuesDATA: "U09 F
Harford FC Hill/Healey - A
MD
CMSA Girls Saturday U09 A/B North
Premier - Top
TID0118"
What am I doing wrong? I tinkered with changing matchfound==false and matchfound=true in the loop, but that still didn't give me the desired result.
MOST RELEVANT SNIPPET
var matchfound = false;
for (var i = 0; i < valuesDATA.length; i++) {
matchfound=false;
for (var j = 0; j < valuesCheckSeeding.length; j++) {
if (valuesDATA[i] == valuesCheckSeeding[j]) {
valuesCheckSeeding.splice(j, 1);
matchfound=true;
continue;
}
}
if (matchfound==false) {
valuesCheckSeeding.push(valuesDATA[i]);
valuesDATA.splice(i, 1);
i=i-1;
}
}
WORKIG SCRIPT EDITED FROM COMMENTS/ANSWERS BELOW
//UPDATE SEEDING SHEET
function updateSeedingSheet() {
var today = Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "MM/dd/yyyy hh:mm a");
//INPUT SHEET INFO
var inputCurrentRow = 4;
var inputCurrentColumn = 20;
var inputNumRows = 1000;
var inputNumColumns =1;
var ssInput = SpreadsheetApp.openById('1Wzg2BklQb6sOZzeC0OEvQ7s7gIQ07sXygEtC0CSGOh4');
var sheetDATA = ssInput.getSheetByName('DATAREF');
var rangeDATA = sheetDATA.getRange(inputCurrentRow, inputCurrentColumn, inputNumRows, inputNumColumns);
var valuesDATA = rangeDATA.getValues();
//SEEDING SHEET INFO
var seedingCurrentRow = 4;
var seedingCurrentColumn = 1;
var seedingNumRows = 1000;
var seedingNumColumns = 1;
var ssSeeding = SpreadsheetApp.openById('1DuCHeZ3zba-nHq-7vYTrylncPGqcA1J9jNyW9DaS3mU');
var sheetSeeding = ssSeeding.getSheetByName('Seeding');
var rangeCheckSeeding = sheetSeeding.getRange(4, 102, 1000, 1);
var columnToClear = sheetSeeding.getRange(seedingCurrentRow, seedingCurrentColumn, seedingNumRows, seedingNumColumns);
var valuesCheckSeeding = rangeCheckSeeding.getValues();
//METHOD TO FILTER
valuesCheckSeeding = valuesCheckSeeding.map(function(e){return e[0];}); //flatten this array
var filteredArr = valuesDATA.filter(function(e){
return !(this.indexOf(e[0])+1);
},valuesCheckSeeding);
Logger.log(filteredArr);
Logger.log(filteredArr.length);
var rangeSeeding = sheetSeeding.getRange(seedingCurrentRow, seedingCurrentColumn, filteredArr.length, seedingNumColumns);
sheetSeeding.getRange('A1').setValue(today);
columnToClear.clearContent();
rangeSeeding.setValues(filteredArr);
/*
//ALTERNATIVE METHOD USING LOOPS
for (var i = 0; i < valuesDATA.length; i++) {
for (var j = 0; j < valuesCheckSeeding.length; j++) {
if (valuesDATA[i][0] == valuesCheckSeeding[j][0]) {
valuesDATA.splice(i, 1);
i--; //account for the splice
break; //go to next i iteration of loop
}
}
}
Logger.log("VALUES DATA:" + valuesDATA);
Logger.log("VALUES CHECK SEEDING: " + valuesCheckSeeding);
//sheetSeeding.getRange('A1').setValue(today);
//rangeSeeding.clearContent();
//rangeSeeding.setValues(valuesDATA); //INCORRECT RANGE HEIGHT, WAS 71 BUT SHOULD BE 1000 - Is splice affecting this?
*/
}//END FUNCTION
V8(ES2016 update):
You can use newer and efficient set class
const array1 = [[1],[2],[3]],
array2 = [[1],[3],[4]],
set = new Set(array2.flat())
console.info(array1.filter(e => !set.has(e[0])))
//expected output [[2]]
You're checking a 2D array. You'd need to use [i][0] and [j][0]
You can try only splicing valuesDATA
Try
for (var i = 0; i < valuesDATA.length; i++) {
for (var j = 0; j < valuesCheckSeeding.length; j++) {
if (valuesDATA[i][0] == valuesCheckSeeding[j][0]) {
valuesDATA.splice(i, 1);
i--; //account for the splice
break; //go to next i iteration of loop
}
}
}
Logger.log(valuesDATA);
Alternatively, try
valuesCheckSeeding = valuesCheckSeeding.map(function(e){return e[0];}); //flatten this array
var filteredArr = valuesDATA.filter(function(e){
return !(this.indexOf(e[0])+1);
},valuesCheckSeeding);
Logger.log(filteredArr);

jQuery Loop - loop count to be used inside loop

I have a set of variables:
var var1 = 0;
var var2 = 0;
var var3 = 0;
var var4 = 0;
var var5 = 0;
And I want to check them all with a for Loop, but I'm not quite sure of the syntax:
for( var i = 1; i<6; i++){
alert(var[i]);
}
that for loop yields no results.
Put them in an array instead.
var vars = [0, 0, 0, 0, 0, 0];
for(var i = 0; i < vars.length; i++) {
alert(vars[i]);
}
If you're defining the varables in the global scope, you can access the values using window['var'+i]:
for(var i = 1; i<6; i++){
alert(window['var'+i]);
}
To access them you would have to use the scope to which they were written. If your code is in the window scope that would then become:
for( var i = 1; i<6; i++){
alert(window['var'+i]);
}
Though of course it's far cleaner if it's in a different scope specific to whatever you're doing. In those cases often
for( var i = 1; i<6; i++){
alert(this['var'+i]);
}
would work.
The data construct you are using is not good for this. Using an array or object is much more feasible for what you want to do as well as being easily extendable.
var arr = [0,0,0,0,0,0];
for (var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
var[i] is used it var is an array. But in your case it isn't. The best way would be to place those values in an array, like;
var myvar = [0,0,0,0,0];
then use the for loop to check for the value.
for( var i = 1;i<6; i++){
alert(myvar[i-1]);
}

Is it possible to create an array and push content in one step

Is there a more concise (i.e. one line) way to do this in Javascript?:
//Media object hasn't been declared yet
var mediaObject.tags = [];
for(var i = 0; i < 100; i++) {
mediaObject.tags.push(entries[i]);
}
EDIT: Here is how my full function looks
var mediaObject = new CustomMedia();
mediaObject.text = entries[k]['text'];
mediaObject.tags = [];
for(var i = entries[k]['tags'].length - 1; i >= 0; i--) {
mediaObject.tags.push(entries[k]['tags'][i]['value']);
}
The last part is what I want to make into one line. Declaring the mediaObject.tags and pushing the content.
Try this:
var mediaObject.tags = entries.slice(0, 100);
If I understand correctly, what you need is Array.map():
mediaObject.tags = entries[k].tags.map(function (t) { return t.value; });

jQuery dynamically increment variable name inside a for-loop

is it possible to add i to a var inside a for-loop?
in wrong syntax it would look like the code below
for(i=1; i<=countProjects; i++){
var test + i = $(otherVar).something();
};
Thanks!
It would be best to use an array for this:
var test = [];
for (i = 1; i <= countProjects; i++) {
test[i] = $(otherVar).something();
};
Then you could access the values like this:
console.log(test[1]);
console.log(test[2]);
etc...
If you have really good reason to have named variables for each value, you can create them like this:
for (i = 1; i <= countProjects; i++) {
window["test" + i] = $(otherVar).something();
};
console.log(test1);
As Mat stated, you should be using arrays for this type of functionality:
var projects = [];
for (var i = 0; i <= countProjects; i++) {
projects.push($(otherVar).something());
}
You could craft variable names, using object["varname"] syntax. But it's _generally_ bad practice:
var varName;
for (var i = 0; i <= countProjects; i++) {
varName = "test" + i.toString();
this[varName] = $(otherVar).something();
}
console.log(test1);

Categories

Resources