Can't pass arrays in multidimensional array to other function using setInterval - javascript

I have a multidimensional array named "thisIsMyContainerArray" that holds content of two other arrays. What I'm trying to do is check each item in the "thisIsMyContainerArray" array and log each item (in this case, two other arrays) from that array separately in the console, and do so every 5 seconds. So far I have the following code:
var thisIsMyContainerArray = new Array();
var thisIsMyArray1 = new Array('val1', 'val2', 'val3', 'val4');
var thisIsMyArray2 = new Array('valA', 'valB', 'valC', 'valD');
thisIsMyContainerArray.push(thisIsMyArray1, thisIsMyArray2);
for (var i = 0; i < thisIsMyContainerArray.length; i++) {
var t1 = setInterval(tester,5000);
function tester() {
console.log(thisIsMyContainerArray[i]);
}
}
And I always get the following output in my console, every 5 seconds:
["val1", "val2", "val3", "val4"]
["val1", "val2", "val3", "val4"]
This is my desired result, I need to see this in the console instead of the output I mentioned earlier:
["val1", "val2", "val3", "val4"]
["valA", "valB", "valC", "valD"]
Any help would be greatly appreciated since I've been stuck on this for a few hours now and I just can't figure it out. :( I tried passing it to the tester function but then it turns out as "undefined".

try this - you should be able to get this working if it is not at the moment..
var thisIsMyContainerArray = new Array();
var thisIsMyArray1 = new Array('val1', 'val2', 'val3', 'val4');
var thisIsMyArray2 = new Array('valA', 'valB', 'valC', 'valD');
thisIsMyContainerArray.push(thisIsMyArray1, thisIsMyArray2);
var t1 = setInterval(tester,5000);
function tester()
{
for (var i = 0; i < thisIsMyContainerArray.length; i++)
{
console.log(thisIsMyContainerArray[i]);
}
}

If I test this code in a clean environment, all it outputs is undefined, so its probably because the i variable isn't passed along, nor contained within a closure scope. Basically, there is an i variable somewhere in the global namespace set to 0, which is the one used.
Also, I'm not sure if you're doing more with the t1 variable, but its being reset at every loop, so you're going to get rogue intervals.
If the logging is all you're after, I'd do this:
var thisIsMyContainerArray = new Array();
var thisIsMyArray1 = new Array('val1', 'val2', 'val3', 'val4');
var thisIsMyArray2 = new Array('valA', 'valB', 'valC', 'valD');
thisIsMyContainerArray.push(thisIsMyArray1, thisIsMyArray2);
var t1 = setInterval(tester,5000);
function tester() {
for (var i = 0; i < thisIsMyContainerArray.length; i++) {
console.log(thisIsMyContainerArray[i]);
}
}
If this is just a simplified example and you need the original structure with a loop and setting multiple intervals for each array, try this:
var thisIsMyContainerArray = new Array();
var thisIsMyArray1 = new Array('val1', 'val2', 'val3', 'val4');
var thisIsMyArray2 = new Array('valA', 'valB', 'valC', 'valD');
thisIsMyContainerArray.push(thisIsMyArray1, thisIsMyArray2);
function tester(index) {
console.log(thisIsMyContainerArray[index]);
setTimeout(function() {
tester(index);
}, 5000);
}
for (var i = 0; i < thisIsMyContainerArray.length; i++) {
tester(i);
}

Related

Updating a common global data-structure using multiple promises in Javascript

Consider the following code:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var globalList = Array();
globalList[0] = "Test";
globalList[1] = "Another Test";
async function coreFunc(promiseName, sleepTime) {
console.log("Started CoreFunc: "+promiseName);
var localList = globalList;
console.log("Length of local array: "+localList.length);
console.log("Length of global array: "+globalList.length);
if (promiseName != "Promise0") {
for (i = 0; i < localList.length; i++) {
console.log(localList[i]);
}
}
if (promiseName == "Promise0") {
var testList = new Array();
testList[0] = "Changed";
globalList = testList;
}
await sleep(sleepTime);
console.log("Length of local array: "+localList.length);
console.log("Length of global array: "+globalList.length);
console.log("Done with CoreFunc: "+promiseName);
}
async function testMultiplePromises() {
var thArray = Array();
for (i = 0; i < 4; i++) {
var pr = new Promise(resolve => coreFunc("Promise" + i, 3000));
thArray[i] = pr;
}
for (i = 0; i < thArray.length; i++) {
await thArray[i];
}
}
globalList is an array that is global. When the above code is invoked like the following:
await testMultiplePromises();
The code goes into an infinite loop. The problem is definitely in the following segment where I am reinitializing the global variable to some different array:
if (promiseName == "Promise0") {
var testList = new Array();
testList[0] = "Changed";
globalList = testList;
}
Is there a way to copy the global datastructure to a local variable without leading to index out of bounds or infinite loop kind of issues? The following code is definitely not doing the job:
var localList = globalList;
What should be done in order to ensure that the Promises either get the older array or get the newer array? To rephrase, how do I make sure the code inside coreFunc (Promise0) that changes the global data structure is protected?
Infinite loop is caused by global i variable on for loops. You should type it like this
...
for (var i = 0; i < localList.length; i++) {
...
for (var i = 0; i < 4; i++) {
...
for (var i = 0; i < thArray.length; i++) {
...
To "protect" array you can just copy it like this
var localList = JSON.parse(JSON.stringify(globalList));
There are a few problems in your code.
var globalList = Array(); - missing the new keyword here.
var localList = globalList; - this does NOT create a copy of the Array, it just creates a reference to the outer array. So whatever you change in localList will also be changed in globalList. Try this: var localList = [...globalList];. This creates a (shallow) copy.
globalList = testList; - same here.
A good read about pass by value vs. pass by reference can be found here.

Generating an array with sub-arrays

I realize this is a somewhat off manner of operations, but for the sake of possibility, I'm wondering if anyone can help?
Here array2 is holding the end state I would like array1 to hold (only I want to do it with the for loop. It's fine that each sub_array's have to be initialized as their own variables, I'm just trying to get the array1 to hold N number of sub_arrays via the loop.
Here is the example I've tried, but trying to "compile" it via a string doesn't allow the sub_arrays to be called in a useable manner.
var numberOfSubArrays = 3
var sub_array1 = []
var sub_array2 = []
var sub_array3 = []
var array1 = []
var array2 = [sub_array1,sub_array2,sub_array3]
for (var i = 0; i < numberOfSubArrays; i++) {
array1[i] = "sub_array" + i
}
Any thoughts would be much appreciated!
var numberOfSubArrays = 3
var sub_array1 = [1]
var sub_array2 = [2]
var sub_array3 = [3]
var array1 = []
// we don't need array2 at all
//var array2 = [sub_array1,sub_array2,sub_array3]
// you need to count from 1..n, as you named your sub_arrays like that
for (var i = 1; i <= numberOfSubArrays; i++) {
// you can use eval, but be careful, eval is evil!
array1[i-1] = eval("sub_array" + i)
}
console.log(array1);
Using eval is yucky. This will work in browsers:
var numberOfSubArrays = 3
var sub_array1 = []
var sub_array2 = []
var sub_array3 = []
var array1 = []
var array2 = [sub_array1,sub_array2,sub_array3]
for (var i = 0; i < numberOfSubArrays; i++) {
array1[i] = window["sub_array" + i + 1];
}
In browsers, "global" vars are really objects in "window".
Note: this will not work in tools like jsfiddle, because they put your code inside a function (that you don't see).

javascript - create new (global) objects with names from array

i am trying to create new Objects with names out of an array.
Without an array i would do:
var object_bruno = new Object();
var object_carlos = new Object();
var object_luci = new Object();
so i will end up with 3 new Objects. But why wont we do that with an loop, which makes it more easy to adde some more Objects later. So i ttried:
// an array full of object names
var obj_arr = [ "object_bruno", "object_carlos", "object_luci"];
// Method one:
for (x in obj_arr) {
alert(obj_arr[x]); // right names shown
var obj_arr[x] = new Object(); //syntax error, dosent work??
};
// Method two:
obj_arr.forEach(function(func_name) {
alert(func_name); // right names
var func_name = new Object(); // no objects are created ???
});
basicly i would prefer to use Method two. i like it because i can fill them late the same way? hopefuly? Any ideas what wents wrong?
You can just loop over the array and assign a new Object to each of the items , like this:
for (var i = 0, l = obj_arr.length; i < l; i++) {
obj_arr[i] = {};
}
UPDATE
You can also do it in this way by applying properties to the global object, for example window:
var people = [ "object_bruno", "object_carlos", "object_luci"];
for (var i = 0, l = people.length; i < l; i++) {
global[people[i]] = {};
}
Using this solution makes the objects global, so you can use them like object_bruno.
Another improvement can be the usage of computed propertiey names of ECMAScript 2015:
var people = [ "bruno", "carlos", "luci"], prefix = 'object_';
for (var i = 0, l = people.length; i < l; i++) {
global[prefix + people[i]] = {};
}
This allows to have more meaningful array.
Note, the global can be the window object in browsers or global object in NodeJS, or perhaps something else in other environments.
Because you are creating a new variable by declaring
obj_arr.forEach(function(func_name) {
alert(func_name); // right names
var func_name = new Object(); // no objects are created ???
});
try this
obj_arr.forEach(function(func_name) {
alert(func_name); // right names
func_name = new Object(); // no objects are created ???
});
var obj_arr = [ "object_bruno", "object_carlos", "object_luci"];
obj_arr.forEach(function(func_name, index, arr) {
arr[index] = {};
});

js Array undefined after json declaration

I m new a web developer and i face up the following problem:
"Cannot read property 'length' of undefined"
my code:
var data=();
for(var i;i<parseInt(window.localStorage["numOfInserts"]);i++){
data["category_name"]=localStorage.getItem(("category_name_"+i).toString());
data["category_id"]=localStorage.getItem(("category_id_"+i).toString());
data["provider_name"]=localStorage.getItem(("provider_name_"+i).toString());
data["provider_id"]=localStorage.getItem(("provider_id_"+i).toString());
data["appointment_date"]=localStorage.getItem(("appointment_date_"+i).toString());
data["appointment_time"]=localStorage.getItem(("appointment_time_"+i).toString());
}
$scope.allAppointments=dataArray;
for(var i=0;i<dataArray.length;i++){
$scope.showme[i]=false;
}
After some research I understand that the problem caused to the fact that data is an array but I try to turn it to json, but
var data ={};
gives me the same error as before.
Please Help me
I think this is what you're looking for, see code comments:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array, using the information
// from local storage. Note that you don't need toString() here.
// Once we've created the object (the {...} bit), we push it onto
// the array
data.push({
category_name: localStorage.getItem("category_name_"+i),
category_id: localStorage.getItem("category_id_"+i),
provider_name: localStorage.getItem("provider_name_"+i),
provider_id: localStorage.getItem("provider_id_"+i),
appointment_date: localStorage.getItem("appointment_date_"+i),
appointment_time: localStorage.getItem("appointment_time_"+i)
});
}
This does the same thing, it's just more verbose and so could help you understand more clearly what's going on:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array
var obj = {};
// Fill it in from local storage. Note that you don't need toString() here.
obj.category_name = localStorage.getItem("category_name_"+i);
obj.category_id = localStorage.getItem("category_id_"+i);
obj.provider_name = localStorage.getItem("provider_name_"+i);
obj.provider_id = localStorage.getItem("provider_id_"+i);
obj.appointment_date = localStorage.getItem("appointment_date_"+i);
obj.appointment_time = localStorage.getItem("appointment_time_"+i);
// Push the object onto the array
data.push(obj);
}
You need to create an array(dataArray before the loop), and create a new object in each iteration and set the property values for that object then add the object to the array like below
var dataArray = [],
data, numOfInserts = parseInt(window.localStorage["numOfInserts"]);
for (var i = 0; i < numOfInserts; i++) {
data = {};
data["category_name"] = localStorage.getItem(("category_name_" + i).toString());
data["category_id"] = localStorage.getItem(("category_id_" + i).toString());
data["provider_name"] = localStorage.getItem(("provider_name_" + i).toString());
data["provider_id"] = localStorage.getItem(("provider_id_" + i).toString());
data["appointment_date"] = localStorage.getItem(("appointment_date_" + i).toString());
data["appointment_time"] = localStorage.getItem(("appointment_time_" + i).toString());
dataArray.push(data)
}
$scope.allAppointments = dataArray;
for (var i = 0; i < dataArray.length; i++) {
$scope.showme[i] = false;
}
It looks like you're trying to create an associative array, so the first line should indeed be
var data = {};
The next part is fine, but then it looks like you want to enumerate the keys
for(var i=0;i<Object.keys(data).length;i++){
$scope.showme[i]=false;
}

Constructing json object using javascript

I am facing issues while constructing an object using javascript. I want this:
{
"p_id": "2",
"p_name": "weblogic",
"ip_list": [
{
"ip_id": 2690
},
{
"ip_id": 2692
},
{
"ip_id": 2693
}
]
}
Below is the javascript code that I am using to get the data into the object:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push("ip_id": selectedArray[index]);
}
I am able to construct the properties for p_id and p_name but struggling to create the the ip_list. Please let me know how to get this constructed using javascript.
Code for posting to the server:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = 2;
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
console.log (secTagJSON);
console.log (JSON.stringify(secTagJSON));
$http.post("http://server:port/api/v1/tags").
success(function(data) {
console.log (data)
});
Simply do this:
var obj = { ip_list: [] };
obj.p_name = "weblogic";
obj.p_id = "2";
for (var i = 0, j = selectedArray.length; i < j; i++)
obj.ip_list.push({ ip_id: selectedArray[i] });
Note that your ip_list is actually an array of objects. So, when you iterate over it, remember that each var item = json.ip_list[i] will return an object, that you can access its properties using: item['ip_id'].
Note that obj is an Javascript object, it is not an JSON. If you want the JSON, you can use JSON.stringify(obj). This will return your JSON (string).
Hope I've helped.
Try:
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
secTagJSON.ip_list = [];
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
you forgot your {} around "ip_id": etc...
You also need to declare that ip_list is an array.
Your ip_list is an array of objects. I would guess that your script was not running as it was.
Posting to your server you should use:
$http.post('server:port/api/v1/tags', secTagJSON).sucess(...

Categories

Resources