cannot set property of multidimensional javascript array - javascript

My JavaScript code is this:
var i=0;
var ret=[];
ret[i][0]=newID;
ret[i][1]=jobTitle;
ret[i][2]=jobText;
ret[i][3]=jobEmail;
ret[i][4]=jobOrder;
These are all strings and all have value.
I'm getting the error:
"Uncaught TypeError: Cannot set property '0' of undefined" on the
first assignment: ret[i][0]=newID;
Also error at jsfiddle
http://jsfiddle.net/Zf9rE/2/
what am I doing wrong?

You must create ret[i] before you try to add elements to it:
var i=0;
var ret=[];
ret[i] = []; // define ret[i]
ret[i][0]=newID;
ret[i][1]=jobTitle;
ret[i][2]=jobText;
ret[i][3]=jobEmail;
ret[i][4]=jobOrder;
Updated fiddle
Unless there is a reason to hard code the array indexes, you might prefer to either create an array literal (as #Rocket shows in the comments) or use Array.prototype.push():
ret[i].push(newID);
ret[i].push(jobTitle);

Another aproach:
var jobTitle="j title";
var jobText = "j desc";
var jobEmail="jemail";
var jobOrder="j order";
var newID="3";
var i=0;
var ret = new Array();
var matrix = new Array()
ret[0]=newID;
ret[1]=jobTitle;
ret[2]=jobText;
ret[3]=jobEmail;
ret[4]=jobOrder;
matrix[i] = ret;
console.log(matrix[0][0]);
Fiddle: http://jsfiddle.net/robertrozas/Zf9rE/6/

Related

Cannot read property 'push' of undefined How to solve?

var item_data = [];
var index = 0;
var data = JSON.parse([{"A":"0","B":"100","C":"0","D":"0"}]);
item_data[index].push(data);
console.log(item_data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Anyone can please help me why it appearing script error in my system it appearing
Uncaught TypeError: item_data[index].push is not a function
How can I solve this issue?
Use assignment operator (=) to insert any item at specific position of an array by using index like:
item_data[index] = data;
OR: If you want to use push() you do not need to use index at all. Because
The push() method adds one or more elements to the end of an array and returns the new length of the array.
item_data.push(data);
var item_data = [];
var index = 0;
var data = JSON.parse('[{"A":"0","B":"100","C":"0","D":"0"}]');
item_data[index] = data;
console.log(item_data);
Change the JSON to string and push that into the array item_data.
var item_data = [];
var index = 0;
var data = JSON.stringify([{"A":"0","B":"100","C":"0","D":"0"}]);
item_data.push(data);
console.log(item_data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Getting error .append is not a function

I am trying to split up a string on /* and then to split up those segments on */
So that I can separate out all of the comments as I want this code to be able to take all of the comments out of the string and then put it back together.
The problem is though I keep getting this .append error which I am pretty sure is because I have made a silly syntax error but I am struggling to find it and any help would be greatly appreciated.
JS
contents = "if for /* else */ . = == === /* return */ function"
var start = /\/\*/gi;
var end = /\*\//gi;
var commentsRemovedSec2 = [];
var commentsRemovedSec1 = contents.split(start);
console.log(commentsRemovedSec1);
for (var i = 0; i < commentsRemovedSec1.length; i++) {
var z = ""
var x = commentsRemovedSec1[i]
var y = x.split(start)
z = y[0]
commentsRemovedSec2.append(z);
};
console.log(commentsRemovedSec2);
Unfortunately .append() isn't an Array method.
Instead use the Array method .push().
commentsRemovedSec2.push(z)
The push() method adds one or more elements to the end of an array and
returns the new length of the array. MDN

Javascript Getting value from exact field from associative array

I have an associative array - indexed by dates. Every element holds another array.
[03/16/2015: Array[3], 03/17/2015: Array[3], 03/18/2015: Array[3], 03/19/2015: Array[3]]
I created it with this code:
array[cellDate][i]=cellText;
How can I get the value for example from cell 03/16/2015 array[2] ??
var text=array['03/16/2015'][2];
With this line of code I got an error.
EDIT:
http://www.traineffective.com/schedule/
I store in that array title of blocks dropped in the schedule (title of block of 'empty' value if cell is empty)
What I want to achive is remeber the order of the blocks for particular weeks , and when user changes week with arrows it loads block based on date withdrowed from array.
Code where I create array :
function saveWeekToArray(array){
var cellDate;
var cellText;
var tmpText;
var i;
workoutsTD.each(function(){
cellDate=$(this).attr("data-day");
array[cellDate]=['','',''];
i=0;
$(this).children('.workout-cell').each(function(){
if (!$(this).hasClass('workout-cell-empty')){
cellText=$(this).find('span').text();
array[cellDate][i]=cellText;
} else {
array[cellDate][i]='empty';
}
i++
});
});
}
Code where I load data from array (One with the error )
function loadBlocksFromArray(array){
var cellDate;
var cellText;
var tmpText;
var i;
workoutsTD.each(function(){
cellDate=$(this).attr("data-day");
i=0;
$(this).children('.workout-cell').each(function(){
if ((array[cellDate][i])!='empty'){
cellText=array[cellDate][i];
$(this).append(createBlock(cellText));
$(this).removeClass('workout-cell-empty');
}
i++;
});
});
}
When you will click sumbit button in console log you will see the structure of array.
I got error while changing the week its :
enter code hereUncaught TypeError: Cannot read property '0' of undefined
In Javascript, there is no concept of an associative array. You either have arrays (which are indexed by numbers) or you have Objects (whose elements are indexed by strings).
What you instead want is an object containing all of your arrays. For example:
var data = {
'3/4/2015' : ['val1', 'val2', 'val3'],
'3/8/2015' : ['val1', 'val2', 'val3']
};
Then you can access your elements in the way that you want:
var ele = data['3/4/2015'][1];
https://jsfiddle.net/x9dnwgwc/
That is the effect what I wanted achive. Thanks for hint Harvtronix!
var jsonObj = { workout : {} }
var i;
var k;
var workoutArray = [];
for(i=1; i<=7; i++){
var newWorkout = i+ "/12/2015";
for (k=0; k<=2; k++){
var newValue = "workoutTitle" + k;
workoutArray[k]=newValue;
}
jsonObj.workout[newWorkout]=workoutArray;
}
console.log(jsonObj);
for(i=1; i<=7; i++){
var newWorkout = i+ "/12/2015";
var tmpArray= jsonObj.workout[newWorkout];
console.log(tmpArray);
}

accessing nested properties based on structure

Could anyone please give me an alternate syntax to the following
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
var i=0;
for(var k in ResultsContainer)
{
var TheArrayOfObjectsThatIneed = ResultsContainer[Object.keys(ResultsContainer)[i]];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
i++;
}
as you see in the image i have an array within an object within an object and i have no idea what the property names are but the structure is always the same {results:{id:{idthatidontknow:[{}]}}} and all i need is to access the arrays
the above code is working nicely but i am new to javescript and i was wondering if there is a nicer syntax and if i am doing it the right way
Perhaps something like this?
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
for(var k in ResultsContainer) {
if (ResultsContainer.hasOwnProperty(k)) {
var TheArrayOfObjectsThatIneed = ResultsContainer[k];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
}
}

javascript copying array to another

i have the following code snippet, where inside for loop the value to contain is not getting assigned, is this is the proper way to copy array to other.??
as here
var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
var groupParam = "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";
var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");
var m=grpNameArr.length;
var contain=new Array();
var cmds=new Array();
var ii;
for(ii=0;ii<(m-1);ii++)
{
contain[ii] = groupCn[ii];
cmds[ii] = grpNameArr[ii];
}
If you want to clone an array you can use slice() method as mentioned in this page:
http://www.hardcode.nl/subcategory_1/article_414-copy-or-clone-javascript-array-object
var oldArray = ["mip", "map", "mop"];
var newArray = oldArray.slice();
your array declaration is wrong , it should be like :-
var groupcn=["All","All","All","All"];
var grpNameArr=["abc","def","ghi"];
you can use :
var contain=groupcn.concat();
var cmds=grpNameArray.concat();
So, after your edit, I see your problem was that you has some typo's in your variable names.
Replace:
var grpNameArr = groupParm.split("#");
var groupcn= groupCondtn.split("&");
With:
var grpNameArr = groupParam.split("#");
// ^ Missing `a` and `r`.
var groupCn= groupCondition.split("&");
// ^ Capital C ^ Missing `i`'s and `o`.
Old Answer
These 2 lines:
var groupcn = All,All,All,All;
var grpNameArr = abc,def,ghi;
Are probably your problem.
What you're doing there is assigning the variable All to a new variable groupcn, then declaring All as a new variable, 3 times.
var groupcn=All,
All, // new variable with the name `All`
All, // new variable with the name `All`
All; // new variable with the name `All`. These 3 override `All`
You'll need to initialize them like this:
var groupcn = [All,All,All,All];
var grpNameArr = [abc,def,ghi];
Other than that, assuming m is the length of groupcn, the code should work.
However, a shorter solution is to copy the arrays like this:
var contain = groupcn.slice();
var cmds = grpNameArr.slice();
Following mistakes were in the code
Using one loop for both the arrays. Since there length is not same two different loops should be used.
There was typo mistake in groupcn variable.
Check this code
<!DOCTYPE html>
<html>
<script>
function chk()
{
var groupCondition = "ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&ALL-OF-THEM&";
var groupParam = "rsTxTraceMsgAside&rsExpTraceMsgAside&rsTxTraceMsgBside&rsExpTraceMsgBside&#hp1TxTraceMsg&hp1ExpTraceMsg&#";
var grpNameArr = groupParam.split("#");
var groupcn= groupCondition.split("&");
var contain=new Array();
var cmds=new Array();
var ii;
for(ii=0;ii<(groupcn.length-1);ii++)
contain[ii] = groupcn[ii];
for(ii=0;ii<(grpNameArr.length-1);ii++)
cmds[ii] = grpNameArr[ii];
alert("groupcn = "+contain);
alert("grpNameArr = "+cmds);
}
</script>
<body onload="chk()">
</body>

Categories

Resources