How to fix code that returns undefined? - javascript

I have this code:
const liked_users = promises[1];
const disliked_users = promises[0];
if (liked_users.length > 0 || disliked_users.length > 0){
for(var i = 0; i < liked_users.length; i++){
for(var j = 0; j < disliked_users.length; j++){
for(var k = 0; k < _USERS.length; k++){
if(_USERS[k].useruid == liked_users[i].likedUseruid || disliked_users[j].dislikedUseruid){
_USERS.splice(i, 1);
i--;
break;
}
basically what is happening is that I access the firebase database and I pull out some data from my objects.
The problem comes where sometimes liked_users is going to be blank and therefore liked_users[i].likedUseruid will return undefined. When they are defined, the code runs fine.
How can I put in some conditional or block of code that allows it to be read in a way that accepts it can be undefined or doesn't run the code until it is defined? I can show more code if it will help.

In JavaScript if you put just variable name in if condition then it will check its available or not.
For example put this block
if(_USERS[k].useruid == liked_users[i].likedUseruid || disliked_users[j].dislikedUseruid){
....
}
in this
if(_USERS[k].useruid && liked_users[i].likedUseruid && disliked_users[j].dislikedUseruid){
....
}
The above condition will check that _USERS[k].useruid is available or not and will continue...
You can make condition as per your need.
I hope this will help you.

Related

Cannot read properties of undefined (reading 'DateTime') even I check there is a data in React.js

I'm just getting learning React a few weeks ago. So, If I ask a pretty general question, I am sorry. But, It would be really appreciated if you help me out!
Issue
: Cannot read properties of undefined (reading 'DateTime')
What I try to solve it
: Firstly, I tried to solve it generally. I mean I add the condition to progress my code and re-render. Also, I check the data exist or not.
Code
const changeWeekendDateColor = () => {
let eventArray = [];
let weekendArray = [];
if (weekendData && weekendData.event && weekendData.schedule) {
let status = false;
const dataEventLength = weekendData.event.length;
const dataWeekendLength = weekendData.schedule.length;
for (let i = 0; i <= dataEventLength; i++) {
eventArray.push(weekendData.event[i].DateTime.split("T")[0]);
}
for (let i = 0; i <= dataWeekendLength; i++) {
weekendArray.push(weekendData.schedule[i].split(" ")[0]);
}
}
for (let i = 0; i <= eventArray.length; i++) {
if (weekendArray.includes(eventArray[i])) return (status = false);
}
return status;
};
console.log(changeWeekendDateColor(weekendData));
WeekendData is this one
What I expect
: I add if statement
if (weekendData && weekendData.event && weekendData.schedule)
So, I think this should be work because if there is no data, it shouldn't do the next line. I am not sure why my code couldn't approach the weekendData.event.DateTime...
for loop can't read undefiened property. dataWeekendLength has 7 length but weekendData.event only have 1 length from the array.
See WeekendData.schedule.length
...
schedule: Array(7)
And this is for loop in the code,
for (let i = 0; i <= dataEventLength; i++) {
eventArray.push(weekendData.event[i].DateTime.split("T")[0]);
}
The for loops 7 times for the dataEventLength,
It's weekendData.event,
...
event: Array(1)
If the for loop goes on i = 1 then it will be weekendData.event[1].
But there is no weekendData.event[1] but only weekendData.event[0].
The code would work but the array only has one.

Break and Continues

I wonder if someone can clarify something for me. I have a bit of code to check an array for overlapping values depending on different values. Basically its the contents of a google sheet in rows and comumns for this is specifically GAS. What I have at the moment is
var e = [[2,4,3,4,2],[1,5,3,6,2],[2,4,3,4,1],[1,4,3,6,1],[2,4,3,6,5]];
var i; //id of entry to check
var j; //id of element to check
var k; //id of entry to compare
for (i in e){ //2D ARRAY ARRAY
for (k in e){ //ELEMENT TO COMPARE
if (e[i][2] === e[k][2] && e[i][3] === e[k][3] && e[i][0] && e[i][0] >= e[k][0] && e[i][1] <= e[k][1] && e[i][4] <= e[k][4] && i !=k){
e.splice(i,1);
continue;
}
}
}
return e;
I had to add the continue; as otherwise if the last array checked was also marked for splice the code failed. But I assumed break would also work in place of continue but for some reason it does not. I thought break would return to the outside loop but does it permanently break that bit of code?
Thanks people
EDIT: spoke too soon. code still fails even with continue. head scratching continues
continue jumps directly to the next iteration, so:
while(true) {
console.log("a");
continue;
console.log("b");
}
will only log a as it will jump back to the beginnig of the loop if it reaches continue.If you however move continue to the last line of the loop (just as in your code) it does nothing as it would jump to the begining to the loop one line later, so it just skips an empty line.
I thought break would return to the outside loop
Yup, thats what happens and that is actually a good thing as if you removed the element already, it won't make sense to check for other dupes as you don't want to remove it twice.
Now the real problem is that splice changes the indexes, so if you splice out the fourth element, the fith element becomes the fourth element, but the loop continues to the fith element without checking the fourth element again (which is now a different one). Therefore you have to go back by one element before you break:
for(let i = 0; i < e.length; i++) {
for(let k = 0; k < e.length; k++) {
if(i === k) continue; // < good usecase
if(/* equality checks */) {
e.splice(i, 1); // remove the element
i--; // go back by one as we changed the order
break; // exit the inner loop
}
}
}
IMO:
1) I would favor for(const [i, value] of arr.entries() over for..in
2) you will forget what arr[i][2] is very soon, giving proper names to the indexes makes it way more readable:
const [idA, someValueA] = e[i];
const [idB, someValueB] = e[k];
if(idA === idB && someValueA <= someValueB // ...
3) e is a bad name.
You can use a labelled break to break out of nested loops.
eg
var num = 0;
outermost:
for(var i = 0; i < 10; i++){
for(var j = 0; j < 10 ; j++){
if(i == 5 && j == 5){
break outermost;
}
num++;
}
}

What happens if you put an iteration count of a for loop as a variable?

I want to make a program in javascript in which a person inputted the iteration count for a for loop(they could input x++, or y--), but I don't know if I am using the right method.
Here is my code:
var x = prompt("iteration count")
// x should equal something like, i++, or x--
for(var i = 0; i < 10; x){
document.write(i)
}
But when the code ran the program kept crashing.
Why is it crashing and how do I fix this?
Please Help
you need to parse the int value of x because it's a string and use it to increment i
var x = parseInt(prompt("iteration count"))
for (var i = 0; i < 10; i += x) {
document.write(i)
}
EDIT :
based on the question edit and the comments, you can use eval(), but :
Do not ever use eval!
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.
So before you use it, read the MDN page and check : eval isnt evil it's just misunderstood
where there's this comment from Spudley :
From a security perspective, eval() is far more dangerous in a server
environment, where code is expected to be fully trusted and hidden
from the end user.
In a browser, the user could eval any code they wanted at any time
simply by opening dev tools, so as a developer you can't get away with
having anything on your client code that could be insecure against
eval anyway.
to test the snippet below, type i++ in the prompt
var x = prompt("iteration count");
for (var i = 0; i < 10; eval(x)) {
console.log(i)
}
an alternative to eval() would be new Function or check the answers here : Programatically setting third statement of for loop
var input = 'i++';//Or whatever condition user passing in
var conditionProgramatically = () => new Function(input)() ;
for (var i = 0; i < 10; conditionProgramatically()) {
console.log(i)
}
For for-loop, third statement will be invoked/executed on every iteration, and hence we set a function call, and in that function, we execute whatever user passing in as you've mentioned i++
That is an endless loop because the variable i never incremented. Try this one.
var x = prompt("iteration count")
for(var i = 0; i < x, i++){
document.write(i)
}
You forgot to increment the index variable, it result to endless loop and maximum stack error, you can also use + for parseInt shorcut.
var x = +prompt("iteration count")
for(var i = 0; i < x;i++){
document.write(i)
}
You have to parse the input value and then make it as a condition to stop iterating after the given value.
var x = parseInt(prompt("iteration count"))
for (var i = 0; i < x; i++) {
document.write(i);
}

Using .push stops for loop from executing

I have a for loop that suddenly stops working when I try to push to an array. The best way to describe what's going on is just to show my code and try an explain what's going on.
for (var i = 0; i < childs.length; i++) {
if (childs[i].length > 0) {
for (var j = 0; j < amountsValue[i].options.custValues.length; j++) {
var label = amountsValue[i].options.custValues[j].label;
var value = amountsValue[i].options.custValues[j].value;
for (var k = childs[i].length - 1; k >= 0; k--) {
if (childs[i][k].attributes[label] != value) {
childBackup.push(childs[i][k]);
childs[i].splice(k, 1);
}
}
}
amountsValue[i].id = childs[i][0].attributes.internalid;
childs.push(childBackup);
}
}
What's happening is I am looping through an array of items which may or may not have custom options available such as different sizes or colours. The loop will check to see if there are any then get the value and label from the array.
After this, we then loop again to try and match up the values with option values stored within a separate model. The plan is to check if the value is the same as the one stored and if not then splice it from the array. The process of elimination should eventually leave only one option left and that will be used to get the internalid.
During this a back up of the spliced objects is kept so that they can be appended to the array again so that the user can change the option they want. The problem is using childs.push(childBackup) stops the browser form reading the options on amountsValue. This works if the code is removed or it is pushed into another index so I'm really not sure why it isn't working.
Does anyone have any suggestions on how to get this working? I'm sorry if this doesn't make much sense, I've tried to explain it as best I can but let me know if anything needs to be cleared up.
EDIT: I have fixed the issue. Thank you to everyone who suggested ways to solve the problem. As others said, I was trying to manipulate the array I was looping through and changing the length on it. So that part of the code was taken outside the loop and after the initial loop another loop was set up which contained the following code:
for (var i = 0; i < childBackup.length; i++) {
childs[0].push(childBackup[i]);
}
It now works as intended. Thank you.
You are manipulating the array you are looping through.
var count = childs.length;
for (var i = 0; i < count; i++) {
if (childs[i].length > 0) {
for (var j = 0; j < amountsValue[i].options.custValues.length; j++) {
var label = amountsValue[i].options.custValues[j].label;
var value = amountsValue[i].options.custValues[j].value;
for (var k = childs[i].length - 1; k >= 0; k--) {
if (childs[i][k].attributes[label] != value) {
childBackup.push(childs[i][k]);
childs[i].splice(k, 1);
}
}
}
amountsValue[i].id = childs[i][0].attributes.internalid;
childs.push(childBackup);
}
}

HTML JAVASCRIPT goto label? [duplicate]

This question already has answers here:
How can I use goto in Javascript?
(16 answers)
Closed 6 years ago.
I need your help, I wish to do a "goto" like "goto" in batch :
:loop1
goto loop1
but in javascript for html page, all my research are useless...
it can be so usefull to know that !
in my case i need this code because i change a the same 'block of code' many times in different function, and there are to much variable to parse ...
so it can help my a lot
here a simple exemple of what i want to do :
for (var i=0; i < 999; i++) {
//some code here
goto go_to_1;
go_to_2:
//some code here
};
for (var i=0; i < 5; i++) {
//some different code here
goto go_to_1;
go_to_2:
//some different code here
};
function mytest () {
for (var i=0; i < 100; i++) {
//again some different code here
goto go_to_1;
go_to_2:
//again some different code here
};
};
go_to_1:
//code here
//always the same code here ,i change it many times
temp = "library"+i+"";
//code here
goto go_to_2;
is that possible ?
how use the "goto" function in javascript ?
Thank for you time
Thank for your help !
JavaScript has NO goto statement, you can only use labels with the break or continue.
You can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.
var i, j;
loop1:
for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1"
loop2:
for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2"
if (i === 1 && j === 1) {
continue loop1;
}
log.innerHTML += ('i = ' + i + ', j = ' + j + "<br/>");
}
}
<div id="log"> </div>
Please Take a look at these:
mozilla developers - js label
stackoverflow - js label

Categories

Resources