Issue while Accessing a Global variable in Javascript - javascript

I am unable to access NatArray[ ] in the second function, and u4count in the second function is coming as 0. What may be the reason?
<script type="text/javascript">
var NatArray = [];
var NatArrayloc = [];
var u4count = 0;
function Check1()
{
NatArray[0] = 202116108;
NatArrayloc[0] = 202116109;
NatArray[1] = 202116111;
NatArrayloc[1] = 202116112;
NatArray[2] = 202116113;
NatArrayloc[2] = 202116114;
u4count = 3;
}
function Check()
{
alert("coming here" + u4count + "natentry" + NatArray[0] );
}
</script>
Thanks in Advance

Works for me as excpected. The order you call your functions is important in this case:
var NatArray = [];
var NatArrayloc = [];
var u4count = 0;
function Check1() {
NatArray[0] = 202116108;
NatArrayloc[0] = 202116109;
NatArray[1] = 202116111;
NatArrayloc[1] = 202116112;
NatArray[2] = 202116113;
NatArrayloc[2] = 202116114;
u4count = 3;
}
function Check() {
alert("coming here " + u4count + " natentry " + NatArray[0]);
}
Check1();
Check();
As some answering users figured out is the unclosed inline comment bad but not the reason for your problem. Something about comments in inline-code
http://fiddle.jshell.net/r8sKf/

You can call this 2 functions in window.onload so it will call second function and also alert and NatArray[ ] value inside alert.
Try something like this:
var NatArray = [];
var NatArrayloc = [];
var u4count = 0;
function Check1() {
NatArray[0] = 202116108;
NatArrayloc[0] = 202116109;
NatArray[1] = 202116111;
NatArrayloc[1] = 202116112;
NatArray[2] = 202116113;
NatArrayloc[2] = 202116114;
u4count = 3;
}
function Check() {
alert("coming here " + u4count + " natentry " + NatArray[0]);
}
window.onload=function(){
Check1();
Check();
};

Here you go:
http://jsfiddle.net/R23eD/
You need to remove the <!-- from your script start. And you're also not calling the Check1() function to initialize the values

Related

.push commant executes "Underfind" from jquery function, how to execute a number?

So the script is really simple, I try to push the dNumber into variable pattern and the results are always "underfined".
when i try to do the same with just push a TEXT for example it's worked.
var level = 0;
var pattern = [];
var userPatern = [];
function dNumber() {
var a = Math.floor((Math.random() * 100 / 25) + 1);
console.log(a);
console.log(pattern);
}
$("body").click(gamestart);
$("body").keypress(gamestart);
function gamestart() {
$("#level-title").text("level " + level);
var x = dNumber();
pattern.push(x);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
var level = 0;
var pattern = [];
var userPatern = [];
function dNumber(){
var a = Math.floor((Math.random()*100/25)+1);
console.log(a);
console.log(pattern);
}
$("body").click(gamestart);
$("body").keypress(gamestart);
function gamestart() {
$("#level-title").text("level " + level);
var x = dNumber();
// pattern.push("alex"); this is work!
pattern.push(x);
pattern.push(dNumber());
//this isn't work what should be number looks like appear as underfined.
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You need to return a from dNumber function so that you can use :)
var level = 0;
var pattern = [];
var userPatern = [];
function dNumber() {
var a = Math.floor((Math.random() * 100 / 25) + 1);
console.log(a);
console.log(pattern);
// return a here if not then it's gonna return undefined by default :)
return a;
}
$("body").click(gamestart);
$("body").keypress(gamestart);
function gamestart() {
$("#level-title").text("level " + level);
var x = dNumber();
pattern.push(x);
console.log(pattern);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Can i call multiple java script functions with in controller?

I defined a JavaScript function using a custom service and I called this function using the service in my controller. This function uses two parameters: The first one is input which I am getting by hitting the below API and the second one is the value of the year which I'm getting using ng-model directive. When I am calling this function in my controller I am getting an error like type is not defined or id is not defined etc. Is it the right way to call a JavaScript function in the controller. Please suggest me.
$http.get("http://152.144.218.70:8080/USACrime/api/crimeMultiple?city=" +$scope.strCity + "&crime=" + $scope.type1 + "&model=" + model).success(function (result) {
$scope.prograssing = false;
console.log("manisha", $scope.strCity);
console.log("kanika", result);
$scope.output = result;
console.log("monga", $scope.output);
$scope.hex = hexafy.year_city($scope.output,$scope.type);
console.log("service", $scope.hex);
});
myapp.js
var app= angular.module("myApp",["ngRoute","leaflet-directive","pb.ds.components"]);
var geomarker = new L.FeatureGroup();
app.service('hexafy', function() {
this.year_city = function (input2,years) {
if(years.toLowerCase()=="all"){
years = "2012,2013,2014,2015,2016,2017,2018,2019";
}
var yrs = years.split(",");
output = {};
outerBoundary = {};
boundary = {};
boundary["boundaryId"] = input[0]["id"];
boundary["boundaryType"] = input[0]["type"];
boundary["boundaryRef"] = "C1";
outerBoundary["boundary"] = boundary;
output["boundaries"] =outerBoundary;
themes = [];
for(var i in input){
crimeTheme = {};
crimeThemeValue = {};
crimeThemeValue["boundaryRef"] = "C1";
result = [];
for(var j in input[i]["prediction"]){
dict = {};
if(yrs.indexOf(input[i]["prediction"][j]["year"])>-1){
dict["name"] = input[i]["prediction"][j]["year"]+" "+input[i]["crime"]+" Crime";
dict["description"] = input[i]["crime"]+" Crime for "+input[i]["prediction"][j]["year"];
dict["value"] = input[i]["prediction"][j]["count"];
dict["accuracy"] = input[i]["accuracy"];
result.push(dict);
}
}
crime = input[i]["crime"].toLowerCase()+"CrimeTheme";
crimeThemeValue["individualValueVariable"] = result;
console.log('crimeThemeValue["individualValueVariable"]',crimeThemeValue["individualValueVariable"]);
crimeTheme[crime] = crimeThemeValue;
themes.push(crimeTheme);
console.log("themes",JSON.stringify(themes));
}
output["themes"] = themes;
console.log(output);
return output;
};
});
});
1) .success and .error methods are deprecated and it is not good to go with it. Instead you'd better use .then(successCallback, errorCallback)
2) To use a service method the proper way is to it like this:
app.service('myService', function() {
var service = {
method:method
};
return service;
function method() {
//Logic
}
})
So in your case the way to go is:
app.service('hexafy', function () {
return {
years_city: function (input2, years) {
if (years.toLowerCase() == "all") {
years = "2012,2013,2014,2015,2016,2017,2018,2019";
}
var yrs = years.split(",");
output = {};
outerBoundary = {};
boundary = {};
boundary["boundaryId"] = input[0]["id"];
boundary["boundaryType"] = input[0]["type"];
boundary["boundaryRef"] = "C1";
outerBoundary["boundary"] = boundary;
output["boundaries"] = outerBoundary;
themes = [];
for (var i in input) {
crimeTheme = {};
crimeThemeValue = {};
crimeThemeValue["boundaryRef"] = "C1";
result = [];
for (var j in input[i]["prediction"]) {
dict = {};
if (yrs.indexOf(input[i]["prediction"][j]["year"]) > -1) {
dict["name"] = input[i]["prediction"][j]["year"] + " " + input[i]["crime"] +
" Crime";
dict["description"] = input[i]["crime"] + " Crime for " + input[i]["prediction"]
[j]["year"];
dict["value"] = input[i]["prediction"][j]["count"];
dict["accuracy"] = input[i]["accuracy"];
result.push(dict);
}
}
crime = input[i]["crime"].toLowerCase() + "CrimeTheme";
crimeThemeValue["individualValueVariable"] = result;
console.log('crimeThemeValue["individualValueVariable"]', crimeThemeValue[
"individualValueVariable"]);
crimeTheme[crime] = crimeThemeValue;
themes.push(crimeTheme);
console.log("themes", JSON.stringify(themes));
}
output["themes"] = themes;
console.log(output);
return output;
}
}
})

how make objects counter via prototype?

I wrote a script, which creates 3 objects. The constructor has a local variable mushroomsCount:
Mushroom = function(num) {
var mushroomsCount = 0;
this.id = num;
this.Create();
}
Mushroom.prototype.Create = function() {
this.mushroomsCount++;
}
Mushroom.prototype.Display = function() {
console.log('mushromms count total is: ' + Mushroom.mushroomsCount);
}
$(document).ready(function() {
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[2].Display(); // first way
Mushroom.Display(); // second way
});
after creating the objects, I try to display the number of the objects at Mushroom.prototype.Display(), but I'm getting undefined.
codepen
You can use a property on Mushroom itselft (like you already had, but not had accessed).
function Mushroom(num) {
this.id = num;
this.create();
}
Mushroom.mushroomCount = 0; // this is public!
Mushroom.prototype.create = function () {
Mushroom.mushroomCount++;
}
Mushroom.prototype.display = function () {
document.write('mushromms count total is: ' + Mushroom.mushroomCount + '<br>');
}
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[0].display();
mushroom[1].display();
mushroom[2].display();
Or use a closure with an IIFE:
var Mushroom = function () {
var mushroomCount = 0;
var f = function (num) {
this.id = num;
this.create();
};
f.prototype.create = function () { mushroomCount++; }
f.prototype.display = function () { document.write('mushromms count total is: ' + mushroomCount + '<br>'); }
return f;
}();
var mushroom = [new Mushroom(0), new Mushroom(1), new Mushroom(2)];
mushroom[0].display();
mushroom[1].display();
mushroom[2].display();
Simple count instances of Mushroom 'class':
function Mushroom(num) {
this.id = num;
Mushroom.count++;
}
Mushroom.count = 0;
Mushroom.prototype.Display = function () {
document.write('mushromms count total is: ' + Mushroom.count + '<br>');
}
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[2].Display();

Javascript gallery with two items at a time

I have this gallery that shows two items at a time, but I was wondering if there's a more elegant way than repeating the same code all the time for the item B in the gallery.
Here's the main code:
var Gallery = new Object();
window.onload = function(){
Gallery.Images = ['red','blue','pink','green','yellow','purple','orange','navy'];
Gallery.CurrentIndexA = 0;
Gallery.CurrentIndexB = 1;
};
Gallery.Next = function(){
if (Gallery.CurrentIndexA < (Gallery.Images.length-1)){
Gallery.CurrentIndexA++;
Gallery.CurrentIndexB++;
console.log("A is:" + Gallery.CurrentIndexA);
console.log("B is:" + Gallery.CurrentIndexB);
}
else {
Gallery.CurrentIndexA = 0;
}
Gallery.Display();
};
Gallery.Prev = function(){
if (Gallery.CurrentIndexA > 0){
Gallery.CurrentIndexA--;
Gallery.CurrentIndexB--;
console.log("A is:" + Gallery.CurrentIndexA);
console.log("B is:" + Gallery.CurrentIndexB);
}
else {
Gallery.CurrentIndexA = (Gallery.Images.length-1);
}
Gallery.Display();
};
Gallery.Display = function(){
var photoA = document.getElementById('photoA');
var photoB = document.getElementById('photoB');
var currentImageA = Gallery.Images[Gallery.CurrentIndexA];
var currentImageB = Gallery.Images[Gallery.CurrentIndexB];
photoA.className = currentImageA;
photoB.className = currentImageB;
};
Here's a fiddle: http://jsfiddle.net/2AdA9/1/
Thanks very much!
If you want to make it look better one thing you could do is something like this.
Gallery.moveUp = function (){
Gallery.CurrentIndexA += 1;
Gallery.CurrentIndexB += 1;
};
Gallery.moveDown = function (){
Gallery.CurrentIndexA -= 1;
Gallery.CurrentIndexB -= 1;
};
Then just call those functions when you want to move up or move back.

Accessing variable outside function

I have a javascript code with functions:
function convertTime()
function loadZive()
Let's say that I have the following code:
function convertTime(){
alert(exampleVariable);
};
function loadZive(){
var exampleVariable = 3;
convertTime();
};
It looks like my convertTime() function can't access exampleVariable. Is there any workaround?
Here is whole code:
function convertTime(publishedDate){
alert(publishedDate);
var date = publishedDate;
var publishedDay = date.toLocaleDateString();
var publishedHour = date.getHours(); //nemozno pouzit toLocaleTimeString (cielovy format ma byt bez sekund)
if (publishedHour < 10){
publishedHour = "0" + publishedHour;
};
var publishedMinute = date.getMinutes(); //nacitanie hodin a minut
if (publishedMinute < 10){
publishedMinute = "0" + publishedMinute;
};
var publishedTime = publishedHour +":"+ publishedMinute; //ich nasledne spojenie do casoveho formatu HH:MM
var publishedDateConverted = publishedDay +", "+ publishedTime;
};
function loadZive(publishedDateConverted){
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.zive.sk/rss/sc-47/default.aspx");
feed.setNumEntries(window.localStorage.getItem("entriesNumber"));
feed.load(function(result) {
if (!result.error) {
var feedlist = document.getElementById("feedZive");
for (var i = 0; i < result.feed.entries.length; i++) {
var li = document.createElement("li");
var entry = result.feed.entries[i];
var A = document.createElement("A");
var descriptionSettings = window.localStorage.getItem("descriptionSettings");
if (descriptionSettings=="true"){
var h3 = document.createElement("h3");
var p = document.createElement("p");
var pDate = document.createElement("p");
pDate.setAttribute("class","ui-li-aside");
var publishedDate = new Date(entry.publishedDate);
convertTime();
pDate.appendChild(document.createTextNode(publishedDateConverted));
h3.appendChild(document.createTextNode(entry.title));
p.appendChild(document.createTextNode(entry.content));
A.setAttribute("href",entry.link);
A.appendChild(h3);
A.appendChild(p);
A.appendChild(pDate);
}
else{
A.setAttribute("href",entry.link);
A.appendChild(document.createTextNode(entry.title));
};
li.appendChild(A);
feedlist.appendChild(li);
}
$("#feedZive").listview("refresh");
}
});
}
google.setOnLoadCallback(initialize);
};
Alert result is Undefined.
PS: exampleVariable isn't defined by the user; it is loaded from a feed, so I cannot define it before the convertTime() function.
As Danny said, or you can also pass variables this way:
function convertTime(exampleVariable){
alert(exampleVariable);
};
function loadZive(){
var exampleVariable = 3;
convertTime(exampleVariable);
};
Remove var from loadZive(), this makes the variable local to loadZive() only.
Alternatively, pass exampleVariable as a parameter to convertTime().

Categories