Javascript function return array undefined [duplicate] - javascript

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.

Related

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]());

JS array length returns 0 [duplicate]

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;
}

How do you save the result of a variable in javascript that is generated by a function?

let's say you have the following Javascript code:
function random() {
var number = (Math.floor(Math.random() * 2));
document.getElementById('number').innerHTML = number;
return number;
};
function searchE(number) {
var english = englishID[number];
document.getElementById('english').innerHTML = english;
};
function searchJ(number) {
var root = root[number];
var masu = masu[number];
var te = te[number];
document.getElementById('root').innerHTML = root;
document.getElementById('masu').innerHTML = masu;
document.getElementById('te').innerHTML = te;
};
function process() {
var number = random();
searchE(number);
searchJ(number);
};
My problem is when the code is that only the random number and the searchE() results are outputted. I believe the problem is that I'm either not doing var result = moof() correctly or not returning a result from moofproperly.
Can somebody please tell me how to make it work? Thank you for your time.
The problem is that here:
function searchJ(number) {
var root = root[number];
var masu = masu[number];
var te = te[number];
vars get hoisted, so to the interpreter, it looks like:
function searchJ(number) {
var root;
var masu;
var te;
root = root[number];
masu = masu[number];
te = te[number];
So when you try to access those arrays/objects in the outer scope (I'm assuming those variables exist in the outer scope, right?), you're actually referencing the currently undefined variables in the inner scope. Use variable names different from the ones used in the outer scope:
function searchJ(number) {
var foundRoot = root[number];
var foundMasu = masu[number];
var foundTe = te[number];

The 'this' context is lost during assignment, but not quite? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 5 years ago.
In the following example there is a simple object. Two instances were created for me to test variable scope.
When test1a (and test2a) is assigned to the method ShowNum it behaves identically as when calling oneObj.ShowNum() by itself. However, when test1b is assigned to the method ShowNum2, then it behaves differently than calling oneObj.ShowNum2() directly.
This is a little puzzling to me because it seems that the 'this' scope is being lost during assignment, but at the same time it is NOT lost because 'num' is still found (and num is as unique to the object instance as this.num2 is).
What is the esoteric explanation for this behavior ?
function TestObject ()
{
var num = 25;
this.num2 = 50;
this.ShowNum = function () {return num;}
this.ShowNum2 = function () {return this.num2;}
this.SetNum = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;
var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2;
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2;
console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());
console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());
Result:
25
50
25
undefined
100
-12
100
undefined
EDIT:
This question does seem like a variant of the one -->here as pointed out by the replies.
My instinctive expectation was that var test1b = oneObj.ShowNum; should imply
var test1b = oneObj.ShowNum2.bind(oneObj); making it for consistent behavior across languages (as Mahesha999 mentioned with the following)
The this keyword behaves differently in JavaScript compared to other
language. In Object Oriented languages, the this keyword refers to the
current instance of the class. In JavaScript the value of this is
determined mostly by the invocation context of function
(context.function()) and where it is called.
Right now I don't feel like pressing further and I consider this matter closed.
Reason :
// you are not assigning the whole object , but just passing refernce to the function
var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2; // so from here it will lose the context of this
test1a is like
function () {return num;}
and test1b is like
function () {return this.num2;}
Here, if you directly assign the function, here this is not pointing to parent function anymore. as you have just assigned the function
You can check that by just putting console.log inside like,
this.ShowNum2 = function () { console.log(this); return this.num2;}
Debugging : Run the below code snippet and you will get idea :
function TestObject ()
{
var num = 25;
this.num2 = 50;
this.ShowNum = function () {return num;}
this.ShowNum2 = function () { console.log(this); return this.num2;}
this.SetNum = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;
var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2;
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2;
console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());
console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());
Solution :
//.bind(parent_object);
var test1b = oneObj.ShowNum2.bind(oneObj);
var test2b = twoObj.ShowNum2.bind(twoObj);
function TestObject ()
{
var num = 25;
this.num2 = 50;
this.ShowNum = function () {return num;}
this.ShowNum2 = function () {return this.num2;}
this.SetNum = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;
var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2.bind(oneObj);
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2.bind(twoObj);
console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());
console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());

setInterval delays

I'm trying to execute a rotating banner (Calling it through an array). I set an interval but the image only shows after 10 seconds (10000) and only then begins the rotation. I removed the cluttered HTML of the array, but here's the rest of it:
var current = 0;
var banners = new Array();
banners[0]=;
banners[1]=;
banners[2]=;
banners[3]=;
var myTimeout = setInterval("rotater()",10000);
function rotater() {
document.getElementById("placeholderlayer").innerHTML=banners[current];
if(current==banners.length-1){
current = 1;
}else{
current += 1;
}
}
window.onload = rotater();
window.onload = rotater;
is the correct syntax. You don't want to call the function. However, the bulletproof solution is rather this:
onload = function() {
rotater();
window.myTimeout = setInterval(rotater, 10000); // Never pass a string to `setInterval`.
};
ProTip™: Don't use new Array(), use an array literal. For example, this:
var arr = new Array();
arr[0] = 'Hello';
arr[1] = 'world!';
Should be written as:
var arr = ['Hello', 'world!'];
Just a comment:
Instead of:
if(current==banners.length-1) {
current = 1;
} else {
current += 1;
}
you can do:
current = ++current % banners.length;

Categories