JQuery ; Declare duplicate global values in - javascript

if i have something like these
var executed = false;
var executed2 = false;
var executed3 = false;
How should i put this in a for loop?

You could make executed a single array rather than a series of variables.
In that case, you could write:
var executed = [];
for(var i = 0; i < 3; i++) {
executed.push(false);
}
Then, to access the values, you can use:
executed[0] === false // ==> true
executed[1] === false // ==> true
executed[2] === false // ==> true

Use Array of Objects instead of using variables in a loop
var executed = [];
for (var i = 0; i < 3; i++) {
executed.push({
status: false
});
}
console.log(executed);

You can declare global variables, use window[]
for(var i = 1; i <= 3; i++) {
window['executed' + ( i > 1 ? i : '' )] = false;
}
// now you can access 'executed', 'executed2', 'executed3' globally
but, DO NOT use global variables if you can.

Related

Can't get i from for ((i = 0; i < koniec.length; i++) to index thru console.log(silnia(5)[i]);

In my JS script, I am trying to index thru silnia() a function that returns an array, I can do that manually without a problem: silnia(5)[1] but when I try to use an i from a for-loop it does not work.
koniec = [1,2,3];
for (i = 0; i < koniec.length; i++){
// Returns only undefined:
console.log(silnia(5)[i]);
// Works no problem:
// console.log(silnia(5)[2]);
}
function silnia(n){
var wynikSilni = [];
for(i = 1; i < (n + 1); i++){
wynikSilni.push(i);
}
return wynikSilni;
}
You're not using a var, let or const statement to declare i, so it is considered a global variable.
Which means the same i you use in the silnia function is the same i being used in the for loop outside of it; essentially, the loop outside of it runs once, the silnia increments i to 6, and once it returns to the for loop in global scope, it stops because i>koniec.length (ETA: It then tries to access sylnia(5)[6] because i equals 6 at that point in time, which is undefined)
Try this:
function silnia(n) {
var wynikSilni = [];
for (var i = 1; i < (n + 1); i++) {
wynikSilni.push(i);
}
return wynikSilni;
}
koniec = [1, 2, 3];
for (var i = 0; i < koniec.length; i++) {
// Returns only undefined:
console.log(silnia(5)[i]);
// Works no problem:
// console.log(silnia(5)[2]);
}
It's 2019 and Arrays have quite a few helpful methods that eliminate the need to set up and manage loop counters, which as others have pointed out, is the source of your problem.
Array.forEach() is the simplest of these and will help to greatly simplify your issue:
koniec = [1,2,3];
// Loop over the knoiec array
// .forEach requires a callback function to execute
// upon each loop iteration. That function will automatically
// be passed 3 arguments: the array item, the item index, the array
koniec.forEach(function(item, index){
console.log(silnia(5)[index]);
});
function silnia(n){
var wynikSilni = [];
for(i = 1; i < (n + 1); i++){
wynikSilni.push(i);
}
return wynikSilni;
}
You need to declare the variables, otherwise you use global variables for all functions.
function silnia(n) {
var wynikSilni = [];
for (var i = 1; i < (n + 1); i++) { // use var or let
wynikSilni.push(i);
}
return wynikSilni;
}
var koniec = [1, 2, 3];
for (var i = 0; i < koniec.length; i++) { // use var or let
console.log(silnia(5)[i]);
}

Make javascript variable can be empty

Hi i have this function below that removes duplicates from the variable suggest but sometimes the data i receive for the suggest variable is empty and the code below wont work beacause of the JSON.parse function how do i make it so that the variable accepts empty data so that the code below will still run without any problems. Any help would be appreciated thanks!
function suggestData(data){
var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.
suggest = JSON.parse(data);
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
You can set suggest inside an if condition to check whether data exists or not
function suggestData(data){
var suggest = [];
if(data){
suggest = JSON.parse(data);
}
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
Also you can simply end the function if you do not want to execute it when data is empty:
function suggestData(data) {
if(!data){
return false;
}
//other code here
...
}
Set the length conditionally as,
var length = suggest? suggest.length: 0;
function suggestData(data){
var suggest = [];
suggest = JSON.parse(data);
var length = suggest? suggest.length: 0;
for (var i = length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
}
suggestData(null);
function suggestData(data){
var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.
if(data)
suggest = JSON.parse(data);
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
Just add the if condition on parsing line like
written in above code::
if(data)
suggest = JSON.parse(data);
The simplest:
if(!data || !suggest)
return;
let array = [1,2,3,8,3,4,4,5]
const removeDuplicateItems = arr => [...new Set(arr)];
console.log(removeDuplicateItems(array))
If you just want to remove duplicated items in an array, you can instead try Set which is quite handy
Even if array is empty or null, this method removeDuplicateItems will still works

Error: columnListA[i] is undefined

When i try to delete some object from columnListA with the objects present in columnListB i'm getting Error: columnListA[i] is undefined
can anyone please tell me some solution for this.
my json list is shown below:
columnListA =[ {id:"a1", value:"XYZ"},{id:"a2", value:"ABC"},{id:"a3", value:"JHI"},{id:"a4", value:"PLM"}]
columnListB =[ {id:"a1", value:"XYZ"}]
My code is this
for ( var j = 0, selLength = columnListB.length; j < selLength; j++)
{
for ( var i = 0, nonSelLength = columnListA.length; i < nonSelLength; i++)
{
if (columnListA[i].id=== columnListB[j].id)
{
columnListA.splice(i, 1);
}
}
}
You're getting this because you're changing columnListA inplace. Since you delete an element, its length passes from 4 to 3, but you still iterate until i = 3.
I suggest creating a new array, instead of changing it inplace and risking this type of error. Example:
columnListA = columnListA.filter(function(nonSel) {
return columnListB.some(function(sel) {
return sel.id !== nonSel.id;
});
});
Array#filter takes a function, and returns a new array that contains only the elements for which the function returns true.
Array#some takes a function, and returns true if the function returns true for all the elements on the array, and false otherwise.
Try:
for ( var j = 0; j < columnListB.length; j++)
{
for ( var i = 0; i < columnListA.length; i++)
{
if (columnListA[i].id === columnListB[j].id)
{
columnListA.splice(i, 1);
}
}
}
JSFiddle
Remove nonSelLength = columnListA.length; i < nonSelLength; from loops and just define variable as less than length of the object

Use an array to check data

I have an array which im using to loop through divs i have stored in variables... but i want to use the values in the array as part of the variable names i wish to check.
Heres an example of what im trying to do:
var data_one = document.getElementById('test'),
data_two = document.getElementById('test2'),
array = ['one','two'];
for (var i = 0; i < array.length; i++) { //error on this line
if(parseInt(data_+array[i]) < 3){
//do something
}
}
But i get this error Uncaught ReferenceError: data_ is not defined
Is there a way to use the array values to act like the variable name some how?
What about:
var data = [
document.getElementById('test'),
document.getElementById('test2')
];
for (var i = 0; i < data.length; i++) {
if(parseInt(data[i]) < 3){
//do something
}
}
or with an object:
var data = {
'one': document.getElementById('test'),
'two': document.getElementById('test2')
};
for (var i in data) {
if(parseInt(data[i]) < 3){
//do something
}
}
Use eval which evaluates string as javascript code
var data_a = 12;
var b = "a";
alert("data_"+b); // alerts data_a
alert(eval("data_"+b)); // alerts 12
See http://jsfiddle.net/ftGhd/
var data_one = document.getElementById('test'),
data_two = document.getElementById('test2'),
array = ['one','two'];
for (var i = 0; i < array.length; i++) {
eval("var curr_array = data_"+array[i]);
if(parseInt(curr_array) < 3){
//do something
}
}

Trying to create objects within a for loop

I'm sure there's a really simple solution to this but I can't wrap my head around it. I'm trying to create and array of objects within a for loop like so:
for(var i = 0; i < 100; i++) {
foos[i] = new Foo(i*10);
bars[i] = someObject.createBar({
x : 0,
y : 0,
foobar = function() {
foo[i].a = true;
}
});
}
When trying to run this I get 'cannot set property a of undefined', both foos and bars are declared earlier in the code as globals.
It works fine if I create foos as foos[0] and access through bars[0]. I suspect it's something to do with function level scoping but as far as i can see the arrays should be accessible on the global object....
You need to "anchor" the value of i. To do this...
for(var i=0; i<100; i++) {
(function(i) {
// now do stuff with i
})(i);
}
Try this:
for(var i = 0; i < 100; i++) {
foos.push( new Foo(i*10) );
bars.push( someObject.createBar({
x : 0,
y : 0,
foobar = function() {
foo[i].a = true;
}
}) );
}
You cannot set value "a" of undefined, because "foo[i]" is undefined. You never defined foo[i]. Did you mean foos[i], maybe?
Also, as others have said, your function foobar is going to use the same value of i for every object you create. You should create a new closure with i, which will allow you to define a local variable i that can be different for each interior function, as so:
for(var i=0; i<100; i++) {
(function(i) {
// now do stuff with i
})(i);
}
The value of i in the execution of foobar is the one at the end of your loop (100). Because the loop block is a closure.
You'd better store the value you want. For example :
for(var i = 0; i < 100; i++) {
foos[i] = new Foo(i*10);
bars[i] = someObject.createBar({
x : 0,
y : 0,
i : i,
foobar: function() {
foos[i].a = true;
}
});
}
Or use a intermediate closure in your loop to enclose i :
for(var i = 0; i < 100; i++) {
(function(i){
foos[i] = new Foo(i*10);
bars[i] = someObject.createBar({
x : 0,
y : 0,
foobar: function() {
foos[i].a = true;
}
});
})(i);
}
The first solution is more explicit, the second one is maybe now more usual.

Categories