JS array length returns 0 [duplicate] - javascript

This question already has answers here:
Wait until all jQuery Ajax requests are done?
(22 answers)
array.length is zero, but the array has elements in it [duplicate]
(2 answers)
Call async/await functions in parallel
(12 answers)
Closed 4 years ago.
Using the following code I call a function ("firstFunction") that generates an Array and returns the array.
async function doProcess() {
const checkState = await firstFunction();
console.log(checkState);
console.log(checkState.length);
return checkState;
}
Using console.log(checkState); I am able to print the data from the whole Array to the console.
When I try to access the values or array data, for example, console.log(checkState.length);, I get 0. What am I doing wrong here?
Edit [added "firstFunction"]:
function firstFunction() {
var array = [];
var url3 = "/Home/CheckPrintService?printer=" + document.getElementById("printerName").value;
$.get(url3, null, function (data3) {
$("#msgPrinterName").html(data3);
var str = $("#msgPrinterName")[0].innerText.toString();
if (str.includes("ERROR CODE")) {
array.push(str);
}
//console.log($("#msgPrinterName")[0].innerText.toString());
});
var e = document.getElementById("ddlViewBy");
var deviceType = e.options[e.selectedIndex].text;
var url2 = "/Home/CheckIfValidIP?input=" + document.getElementById("ipAddress").value + "&type=" + deviceType;
$.get(url2, null, function (data2) {
$("#msgIPPort").html(data2);
var str = $("#msgIPPort")[0].innerText.toString();
if (str.includes("ERROR CODE")) {
array.push(str);
}
});
var url = "/Home/CheckPrinter?printer=" + document.getElementById("printerName").value;
$.get(url, null, function (data) {
$("#msgPrintService").html(data);
var str = $("#msgPrintService")[0].innerText.toString();
if (str.includes("ERROR CODE")) {
array.push(str);
}
});
return array;
}

Related

How to get length of array inside of objects in javascript? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 11 months ago.
Try to get length of array inside an object
image above is return of Res
I want to check if every tenor length is equal or more than zero.
But, I stuck in how to call itemCounter"i" when loop it
var tenorCount = Object.keys(res).length;
var flagTenor = false;
try{
for(var i=1;i<tenorCount;i++){
if (res.itemCounter_+i.tenor.length < 1){ //Stuck in here
flagTenor = true;
}
}
}catch(e){
console.log(e);
}
How to call itemCounter"i" correctly?
Try like this using template literals and computed property names
if (res[`itemCounter_${i+1}`].tenor.length < 1)
Example
const res = {
itemCounter_1: {
tenor: ["one"]
},
itemCounter_2: {
tenor: []
},
}
var tenorCount = Object.keys(res).length;
var flagTenor = false;
try {
for (var i = 0; i < tenorCount; i++) {
if (res[`itemCounter_${i+1}`].tenor.length < 1) {
flagTenor = true;
}
}
} catch (e) {
console.log(e);
}
console.log(flagTenor);

Is there a way to call a function through using a string that matches its name? [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 2 years ago.
This is what I have attempted, and may give a better gist of the question I'm trying to ask:
var x = "run";
var y = "Function";
var xy = x + y;
function runFunction() {
console.log("Function has been called.");
}
xy();
What am I doing wrong here?
You could use eval(), but don't. Instead, store your functions in an object:
const functions = {
greetingOne: () => console.log("Hello!"),
anotherGreeting: () => console.log("Hi there!");
};
const f = "greetingOne";
functions[f]();
It is possible if the function lives on an object.
const obj = {
runFunction: function() {console.log('hello')}
}
var x = "run";
var y = "Function";
var xy = x + y;
obj[xy]();
You can call eval that run string as Javascript code
function runFunction() {
console.log("Function has been called.");
}
functionName = 'runFunction'
eval(functionName + '()');
All global functions stores in window object.
let first = "first";
let second = "Second";
let xy = first+second;
function firstSecond() {
return "Hello World";
}
console.log(window[xy]());

Why is return coming back as undefined? [duplicate]

This question already has answers here:
Return value of recursive function is 'undefined'
(1 answer)
Getting return undefined on recursive function javascript
(4 answers)
Closed 5 years ago.
In this code I have written, y comes back as undefined. I've looked everywhere I can think of to figure out what I did wrong, but as far as I can tell it's correctly written. It's supposed to come back as 00085.
function ab()
{
var x = 85 + '';
var y = AddCorrect(x);
}
function AddCorrect(add)
{
if (add.length < 5)
{
var corrected = '0' + add;
AddCorrect(corrected);
}
else
{
return add;
}
}
You pass a number but your function expect a string (you're checking add.length). You have also to return something inside if (add.length < 5):
function ab()
{
var x = 85;
var y = AddCorrect(x); // <-- x is a number
console.log(y);
}
function AddCorrect(add)
{
add = '' + add; // <--- Convert the number to string
if (add.length < 5) // <--- so you can check the length
{
var corrected = '0' + add;
return AddCorrect(corrected); // <--- return here
}
else
{
return add;
}
}
ab();

Javascript function return array undefined [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 a function loadTileSet(). This function must return arrTiles (image data array), but function is returning UNDEFINED. I'm using push to put data into array..
function loadTileSet(){
var canvas = document.getElementById('fakeCanvas');
$('#fakeCanvas').hide();
var ctx = $("canvas")[0].getContext('2d');
var imgTileSet = new Image();
imgTileSet.src = 'tileset.png';
var imageTileNumWidth = 23;
var imageTileNumHeight = 21;
var arrTiles = [];
imgTileSet.onload = function(){
var imageWidth = imgTileSet.width;
var imageHeight = imgTileSet.height;
sndCanvasWidth = imageWidth/imageTileNumWidth;
sndCanvasHeight = imageHeight/imageTileNumHeight;
canvas.width = imageWidth;
canvas.height = imageHeight;
ctx.drawImage(imgTileSet,0,0,imageWidth,imageHeight);
var i=0;
var j=0;
var t=0;
for(i=0;i<imageWidth;i+=sndCanvasWidth){
for(j=0;j<imageHeight;j+=sndCanvasHeight){
var myImageData = ctx.getImageData(j,i,sndCanvasWidth,sndCanvasHeight);
arrTiles.push(myImageData);
}
}
return arrTiles;
}
}
and here I try to put array into another
var arrNew = loadTileSet();
console.log(arrNew[0]);
Bergi's comment already states the problem. This is an async process, so you need to handle it as one. The general idea is to use a callback:
function loadTileSet(callback) {
// ...
imgTileSet.onload = function () {
// instead of return, do this
callback(arrTiles);
};
}
loadTileSet(function (arrNew) {
// now you can use arrNew
});
your function doesn't return anything. Also, where you are populating the array, it is encapsulated in that .onload function.

Multidim json array javascript, how to grab values

I have this data response from an AJAX call:
{"18:00":{"twopersons":1,"fourpersons":0}}
Which gets stored into a variable by statsarray = data;
Now how can i loop through statsarray and output the twopersons value?
So I can alert:
18:00 - There's 2 x 2persons and 0 x 4persons
Here is the Ajax call:
var statsarray;
var currentloopeddate = test_date.toString('yyyy-MM-dd')
$.post("/home/sessions",
{ action: 'partner_calendar_checkseats', date: currentloopeddate },
function(data) { statsarray = data; }
);
Just do the following:
var twopersons = data["18:00"].twopersons;
var fourpersons = data["18:00"]["fourpersons"];
(Both variants are possible)
A variant would be:
var shorter = data["18:00"];
var twopersons = data.twopersons;
// ...
Something like:
var tst = {"18:00":{"twopersons":1,"fourpersons":0}};
for(k in tst) {
for(var z in tst[k]) {
console.log(k + ": Theres "+tst[k][z] + " X " + z);
}
}
You can try something like this:
(UPDATE: better example)
var statsarray = {"18:00":{"twopersons":1,"fourpersons":0}};
var hour, persons, line, array;
for (hour in statsarray) {
if (statsarray.hasOwnProperty(hour)) {
array = [];
for (persons in statsarray[hour]) {
if (statsarray[hour].hasOwnProperty(persons)) {
array.push(statsarray[hour][persons] + " x " + persons);
}
}
line = hour + " - There's " + array.join(' and ');
alert(line);
}
}
See: DEMO.
Unfortunately you have to test with .hasOwnProperty to make sure it will work with some libraries.
UPDATE: You have added the code from your AJAX call in your question and I noticed that you declare the statsarray variable outside the callback function, but assign some value to that variable inside the callback. Just keep in mind that you have to run your iteration code inside the function that is the AJAX callback, where you have: statsarray = data; - just after this line, to make sure that you actually have some values to iterate over.

Categories