How to get array index values in Javascript [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
Hi I can't get the value of a specific index of an array. I don't know why because if I try to log the entire array it works but with a specific index it doesn't work
This is my code, I use cloud firestore to get the ID of a document and save it into array
var idUsers = [];
const users_list = document.querySelector("#users_list");
db.collection("utenti").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
users_list.innerHTML += "<a href='utente.html' class='collection-item black-text'>" + doc.data().nome + " " + doc.data().cognome + " " + " </a>";
idUsers.push(doc.id);
});
});
console.log(idUsers);
console.log(idUsers[0]);
This is the result in Chrome console
enter image description here

Although it is considered to be a confusing statement, I assume that the operation is running asynchronously. Try to put a delay and then find value of idUsers[0] in order to find out the assumption.

Related

Printing/console logging from map object [duplicate]

This question already has answers here:
How to iterate over Object's property-value pairs?
(8 answers)
Closed 1 year ago.
Lets say I have personalRecords parameter.. and it accepts this map object:
new Map([['100', 9.58], ['200', 19.19]])
I want to take these numbers and print them out / console.log in VSCode in such format:
100m: 9.58s
200m: 19.19s
I can't seem to figure out how to take these numbers out of the object and print them out properly. I appreciate your help in advance.
You can use for each to achieve that
const personalRecord = new Map([['100', 9.58], ['200', 19.19]])
for(let record of personalRecord){
console.log(record[0] + "m: " + record[1] + "s")
}

jQuery-UI Dialog only showing last iteration of the for loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 4 years ago.
Don't know if I'm being blind but every time I look at this code the logic makes sense. I am trying to iterate through this for loop and for each iteration generate a dialog box with the ID of #dialog-(i) but it only show's the last iteration of 200. The code is below:
var i;
for(i=1;i<200;i++){
$("#dialog-" + i).hide();
$('#meetings_box-' + i).click(function() {
var dialog = $("#dialog-" + i).dialog();
if (dialog) {
console.log('yay');
console.log(dialog);
} else {
console.log('nay');
}
});
};
Any help to finding the issue, probably something really dumb
This is because click will happen sometime in the future and by then the loop has already finished it's execution and the value of i is updated to the last value. Instead of var you can use let

empty array is returned even after pushing value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have declared an empty array called answerDataArray and pushed values into the array (values are snapshots from firebase DB). When I can use console.log(answerDataArray) outside the forEach loop it showing an empty array but when I do console.log(answerDataArray) anywhere inside the forEach loop I get the populated array. Please tell what happening here.
var ideationContestRef = ideationDataRef.child(contestDataRef.key);
ideationContestRef.once("value", function(snapshot){
if(snapshot.child("answers").exists()){
snapshot.child("answers").ref.once("value", function(snapAnswerKey){
var answerKey = Object.keys(snapAnswerKey.val());
var answerDataRef = db.ref("answerData");
var answerDataArray = [];
answerKey.forEach(function(key){
answerDataRef.child(key).once("value", function(snapAnswerData){
answerDataArray.push(snapAnswerData.val());
});
});
console.log(answerDataArray);
// res.render("ideation", {id: contestId, layout: 'styled.handlebars', page: 'ideation', user_logged_in: user_presence, contestData: snapshot.val(), answerDataArray: answerDataArray});
});
}
Your problem probably is the fact that answerDataRef.child(key).once("value", function(snapAnswerData){ is async, therefore you can't expect to have values line after the forEach that you have mentioned.
Maybe you can use Promise in order to return async value.

Nodejs - Can't get a property from JavaScript object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
New to nodejs and really programming in general except some basic PHP. I think my problem is more basic javascript than anything though.
How can I access variables 'latitude' and 'longitude' outside the object 'img'?
console.log(latitude + '|' + longitude) is displaying the data I want but in console.log(img) all img properties are empty including exifData.gps.GPSLatitude & exifData.gps.GPSLongitude.
var ExifImage = require('exif').ExifImage;
var img_loc = 'c:/node/test/wherepic/uploaded_imgs/img.JPG';
var img = new ExifImage({ image : img_loc }, function (error, exifData) {
var latitude = exifData.gps.GPSLatitude;
var longitude = exifData.gps.GPSLongitude;
console.log(latitude + '|' + longitude);
});
console.log(img);
The problem is not the object, but the fact that your second console.log is executed before the data becomes available. Only when the function is called that data becomes available. You must access it inside the function.

Simple Javascript Replace not working [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 3 years ago.
This seems so simple and trivial but it is not working. Here is my javascript:
var url = "/computers/";
console.log(url);
url.replace(/\//gi, " ");
console.log(url);
And here is the output in my browsers console:
/computers/
/computers/
As you can see nothing changes. As you can tell from the code I'm trying to replace the forward slashes with spaces. What am I doing wrong?
url = url.replace(/\//gi, " ");
Nothing changes because you're not assigning the result of the replacement to a variable. Add url = url.replace()
url.replace(/\//gi, " "); returns the resulting string (in javascript you can't modify an existing string), you are not assigning it to anything
assign it like so:
url = url.replace(/\//gi, " ");

Categories

Resources