Why does the array reference number switch to a STRING? - javascript
I found the problem I was having with referencing but I don't understand what's happening now. The array is being populated properly but I couldn't figure out why I couldn't pull the values. Then after some trial and error I found at the end if I closed the array reference value in quotes it would return the right value. Why is the reference being turned into a string when it's created using an integer?
function initPPArray(year) {
var beginningOfYear = new Date('January 1, 2014');
var dayOffset = (beginningOfYear.getDay() + 6) % 7;
var beginningOfPP = new Date(beginningOfYear.getFullYear(), beginningOfYear.getMonth(), beginningOfYear.getDate() - dayOffset);
var payPeriodList = [];
payPeriodList[1] = {};
payPeriodList[1].start = beginningOfPP;
payPeriodList[1].end = new Date(beginningOfPP.getFullYear(), beginningOfPP.getMonth(), beginningOfPP.getDate() + 13);
Logger.log('beginningOfPP: ' + beginningOfPP);
var txtStart = getMonthString(payPeriodList[1].start) + ", " + payPeriodList[1].start.getDate();
var txtEnd = getMonthString(payPeriodList[1].end) + ", " + payPeriodList[1].end.getDate();
Logger.log("PP 1: " + txtStart + " - " + txtEnd);
for (var i = 2; i <= 26; i++) {
payPeriodList[i] = {};
payPeriodList[i].start = new Date(payPeriodList[i-1].end.getFullYear(), payPeriodList[i-1].end.getMonth(), payPeriodList[i-1].end.getDate() + 1);
payPeriodList[i].end = new Date(payPeriodList[i].start.getFullYear(), payPeriodList[i].start.getMonth(), payPeriodList[i].start.getDate() + 13);
var txtStart = getMonthString(payPeriodList[i].start) + ", " + payPeriodList[i].start.getDate();
var txtEnd = getMonthString(payPeriodList[i].end) + ", " + payPeriodList[i].end.getDate();
Logger.log("PP: " + i + ": " + txtStart + " - " + txtEnd);
}
// This returns the proper value.. when no quotes are used it returns
// the last date of the loop "Dec 15,2014"
Logger.log("Random Value: " + payPeriodList["6"].start)
return payPeriodList;
}
Arrays in JavaScript start with index 0, not index 1. So this code:
var payPeriodList = new Array();
payPeriodList[1] = {
// ...
};
...leaves the 0th entry blank while making the array's length 2 (because standard JavaScript arrays are inherently sparse, as they aren't really arrays at all). Once you've done that, since you're using push in the subsequent code, that first entry is never filled in.
Change the 1 to a 0, or use push for the first entry (as you are with the subsequent ones).
Side note: It's almost always better to create an array with an array literal, not new Array():
var payPeriodList = [];
I think that your problem is that every item in your payPeriodList array is a reference to the same object (payPeriodItem). Each iteration through your assignment array is altering the start and end values of payPeriodItem instead of creating a new object with new start and end values. So to solve this, you would need only change the first line inside the for loop to assign a new object to payPeriodList[i].
for (var i = 2; i <= 26; i++) {
payPeriodList[i] = {};
/*...*/
}
Related
How to know when a for loop is done without knowing how many iterations there will be?
using a for-loop in javascript i´m getting a not known amount of id´s, they´re not in an array but coming one by one. is there a way to get an alert when there are no more id´s to retrieve meaning the for loop is done? i can´t wrap my head around this, any help would be greatly appreciated. thanks! edited with code for clarification. function iterateDevices(api) { var count = api.getcount("devices"); var apiPath = dequotePath(api); for (var i = 0; i < count; i++) { var deviceApi = new LiveAPI(apiPath + " devices " + i); if (deviceApi) { var deviceName = deviceApi.get("name"); var deviceid = deviceApi.id; //var deviceName = deviceApi.get("parameters"); var className = deviceApi.get("class_name"); var deviceApiPath = dequotePath(deviceApi); var chainsCount; var chainApi; var j; if ((className == "DrumGroupDevice") || (className == "AudioEffectGroupDevice") || (className == "InstrumentGroupDevice")){ //post(deviceName + " id " + deviceid + "\'\n"); //outlet(0,deviceid); // arr.push(deviceName); if (deviceApi.get("can_have_chains") == 1) { chainsCount = deviceApi.getcount("chains"); // only racks have chains for (j = 0; j < chainsCount; j++) { // post("id" + deviceid + " found device " + deviceName + " at path \'" + deviceApiPath + "\'\n"); //outlet(0,deviceid); chainApi = new LiveAPI(deviceApiPath + " chains " + j); iterateDevices(chainApi); myFunction(); } chainsCount = deviceApi.getcount("return_chains"); // only racks have chains for (j = 0; j < chainsCount; j++) { //post("2 found device " + deviceName + "id"+deviceid + " at path \'" + deviceApiPath + "\'\n"); // outlet(0,deviceid); chainApi = new LiveAPI(deviceApiPath + " return_chains " + j); iterateDevices(chainApi); } } } } } } iterateDevices.local = 1;
The purpose of a for loop is to deal with a known number of iterations. If you want to deal with an unknown number of iterations, you would use a while loop. Of course, this is programming, so lets look at the crazy things we can do: Iterate over a collection. We dont necessarily know how many things are in the collection, but we may want to iterate over all of them. The number of things in the collection might even change as we're iterating. We can change how we iterate through the loop. That whole i++ part? What if we replace it with i += 2? Or what if it's i -=1? Or i += j and j changes while we're iterating? We can change how we break out of the loop. You can put a break statement in there to break out of the loop anytime. You can also change the conditional of the loop. What if i < 100 is replaced by i<j? Or what if we replace it with i<100 || q == true?
You may use a while loop instead of a for and insert a condition to terminate the loop. Using pseudo-code, you could do something like: other_ids = True // boolean var while(other_ids) { // do what you have to do other_ids = FuncionToCheckWhetherThereAreNewIds } FuncionToCheckWhetherThereAreNewIds should be a function that gives you true if there are new ids and false if there are not.
Can't get objects inside of array
I have been trying to use JavaScript array to push my object by header like this : var tab_temp = new Y.TabView( { srcNode: '#' + tabId } ); tabsArray['"' + type + "_" + subTypes + '"'] = tab_temp; Let's type = "x" and subTypes = "y", so I was expecting the object when I write something like: tabs["x_y"] But there is problem with this. When I debug, I can see this array will hold an object "x_y" but length of the array is 0 I can't use push also because in that way I need to use index to get it back but it is tough since sequence might change. Edit 1: I am using this because I want to hold a couple of TabView objects. Otherwise I can't reach those object after they created. (AlloyUI). I was able to push those object inside of array. As you see "Baru_BARANG" include and object that start with: s Edit 2: Thanks for help, I fixed it. I used Object instead of Array for this: var tabs = {} tabs[x + "_" + y] = "z"; I get the value by tabs[x + "_" + y]
You really need to be reading more about working with objects in JavaScript. Try here first. var type = "x"; var subType = "y"; var tabsArray = {}; tabsArray[type + "_" + subType] = "z"; console.log("tabsArray = "); console.log(tabsArray); console.log("tabsArray['x_y'] = " + tabsArray["x_y"]); // output: z // Including code added to question as a comment: var tabsArray = []; var x = "x"; var y = "y"; tabsArray[x + "_" + y] = "z"; console.log("tabsArray['x_y'] = " + tabsArray["x_y"]); // tabsArray.length will still be 0. To set .length you can use: for (var i = 0; i < tabsArray.length; i++) { tabsArray.length = ++i; }; console.log("tabsArray.length = " + tabsArray.length);
You are most likely instantiating tabsArray as an array, i.e. var tabsArray = [];. This results in the observed behavior. Since you want to define the keys yourself, you should instantiate it as an object instead: var tabsArray = {}; tabsArray['x_y'] = 'z'; More about working with objects in JavaScript.
Pull information from a data file?
I have over 170000 entries of data in data file in this format: 1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;: 1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;: Now each data array starts with a unique id and i was wondering is there a convenient way to push each entry 1479661 then 1479662 every second to an array and assign the values within the unique id into 6 fields that update. Now I ask if there is a more convenient way as currently I am using this method: Data comprises of three chunks in a single line Split the link into chunks var chunkOne = [1479661]; var chunkTwo = [-1,1,-1,-898,-769,0.00,-1,2,-1,-96,-1402,0.00,-1,3,-1,117,-1397,0.00,-1,4,-1,-4,-2420,0.00,4,5,-1,5570,4395,0.00,4,6,-1,5570,4395,0.00,4,7,-1,5570,4395,0.00,4,8,-1,5570,4395,0.00,4,9,-1,5570,4395,0.00,4,10,-1,5570,4395,0.00,4,11,-1,5570,4395,0.00,4,12,-1,5570,4395,0.00,4,13,-1,5570,4395,0.00,4,14,-1,5570,4395,0.00,-1,15,-1,913,-3533,0.00,4,16,-1,5570,4395,0.00,4,17,-1,5570,4395,0.00,4,18,-1,5570,4395,0.00,4,19,-1,5570,4395,0.00,4,20,-1,5570,4395,0.00,4,21,-1,5570,4395,0.00,4,22,-1,5570,4395,0.00,4,23,-1,5570,4395,0.00,4,24,-1,5570,4395,0.00,4,25,-1,5570,4395,0.00,4,26,-1,5570,4395,0.00,4,27,-1,5570,4395,0.00,4,28,-1,5570,4395,0.00,4,29,-1,5570,4395,0.00]; var chunkThree = [117,-1397,7,7.00,"A","Dead"]; Then get length of each array: var chunkOneLength = chunkOne.length; var chunkTwoLength = chunkTwo.length; var chunkThreeLength = chunkThree.length; Pick out the nth value in the array depending on the data chunk: //uniqueID set as first for (var i = 0; i < chunkOneLength; i = i + 1) { // useful code would go here alert("This is the unique ID " + chunkOne[i]); } //teamval for (var i = 0; i < chunkTwoLength; i = i + 6) { // useful code would go here alert("This is the teamVal " + chunkTwo[i]); } Now the only problem I see with this method, is that the original data array will need to be formatted and separated into chunks every time.
As you have a separator on each section i.e. : you can actually use split to split them up like below and push them into a array and only have to do 2 loops - firstly pushing the split data in a new array and then looping through them and populating the structure. Please note as long as each chunk of data is separated with : this will work with anything even if you expand the data later. obviously it will not work if you remove the : separator. example below: var splitChucks = []; var chucks = [ "1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:", "1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:"]; for (var i = 0; i < chucks.length; i++){ splitChucks.push(chucks[i].split(':')) } for (var h = 0; h < splitChucks.length; h++) { alert("This is the unique ID " + splitChucks[h][0]); alert("This is the teamVal " + splitChucks[h][1]); } Hope this helps, this is a much more efficient way to do your task :)
var splitChucks = []; var chucks = [ "1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:", "1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:"]; for (var i = 0; i < chucks.length; i++){ splitChucks.push(chucks[i].split(':')) } for (var h = 0; h < splitChucks.length; h++) { alert("This is the unique ID " + splitChucks[h][0]); alert("This is the teamVal " + splitChucks[h][1]); }
One of the best purposes of an unique ID is to act as an index. So, instead of iterating over your index array (chunkOne), use ID as an Object key! // 1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;: var data = { 1479661: [ -1,1,-1,-898,-769,0.00,-1,2,-1,-96,-1402,0.00,-1,3,-1,117,-1397,0.00,-1,4,-1,-4,-2420,0.00,4,5,-1,5570,4395,0.00,4,6,-1,5570,4395,0.00,4,7,-1,5570,4395,0.00,4,8,-1,5570,4395,0.00,4,9,-1,5570,4395,0.00,4,10,-1,5570,4395,0.00,4,11,-1,5570,4395,0.00,4,12,-1,5570,4395,0.00,4,13,-1,5570,4395,0.00,4,14,-1,5570,4395,0.00,-1,15,-1,913,-3533,0.00,4,16,-1,5570,4395,0.00,4,17,-1,5570,4395,0.00,4,18,-1,5570,4395,0.00,4,19,-1,5570,4395,0.00,4,20,-1,5570,4395,0.00,4,21,-1,5570,4395,0.00,4,22,-1,5570,4395,0.00,4,23,-1,5570,4395,0.00,4,24,-1,5570,4395,0.00,4,25,-1,5570,4395,0.00,4,26,-1,5570,4395,0.00,4,27,-1,5570,4395,0.00,4,28,-1,5570,4395,0.00,4,29,-1,5570,4395,0.00,117,-1397,7,7.00,"A","Dead" ] // More data... }; Object.keys(data).forEach(function(key) { console.log('This is ID ' + key); data[key].forEach(function(value,index,array) { console.log('Index ' + index + ' of data key ' + key + ':'); console.log(data[key][index]); }); }); Test this on any modern browser's console or node.js instance to see results.
why is my array.length not increasing?
Doesn't the addition of an array element by push increase the length of the array by 1 ? var parameters = []; if (parameters.length == 0) { // join select menu and option then add to parameters array var parameterSelected = nameOfSelectBox + " " + ":" + " " + $i + ","; parameters.push(parameterSelected); } else { var parameterSelected = "," + " " + nameOfSelectBox + " " + ":" + " " + $i; parameters.push(parameterSelected); } // check for repeats // does a select input exist? // add to appropriate indexes then add new or modify existing parameters console.log(parameters.length); });
In your current code it will never go to else because var parameters = []; always sets its length to 0 because you just declare parameters again. Then you add one element to the array and its length changes to 1 and that is it.
you should do something like this: var my_array = []; // zero my_array.push("abc"); // one my_array.push("def"); // two
Javascript multidimensional array updating specific element
I have a string that has been converted into an 2D Array in js. board = "...|.X.|...|" It is used to represent a game board each . represents a space each | represents a row each X represents a wall EDIT: code below for the 2d array creation var src= "...|.X.|...|"; board = src.split(/\|/g); for (var i = 0; i < board.length; i++) { var cells = board[i].split(''); for (var j = 0; j < cells.length; j++) { cells[j] = parseInt(cells[j]); } board[i][j] = cells; console.log(board[1][1]) //returns 'X' when i access board[i][j] it returns correctly: [0][0] = "." [1][1] = "X" [1][2] = "." etc etc I want to update the specific element with a string representing a piece. However when i insert into an element like so: board[0][0] = "piece4" The array returns in firebug as so: board = "piece4|.X.|...|" When it should look like: board = ".piece4.|.X.|...|" Why are elements [0][1] and [0][2] being overwritten? Am I not understanding arrays of array index access correctly in js?
I just had the same problem, but it had a more complex reason and I want to add it, in case someone finds this page searching for the same problem I had: I had created and filled a 2-dimensional array like this: var foo = Array(n).fill(Array(n).fill(0)); which creates a 2-dimensional n*n array filled with zeroes. Now when I tried to overwrite a cell like this foo[1][1] = 1; I ended up with these values: [[0,1,0], [0,1,0], [0,1,0]] which is really surprising IMHO. The reason for this was, that there has only been one row, which had internally been referenced three times. So when I changed the first index in "the second" row, it effectively changed all rows. Bottom line: don't use Array.fill to create multi-dimensional arrays!
PROBLEM: I'm betting that you have a one-dimensional array with strings stored in each. So your array actually looks like: array ( [0] => '...', [1] => '.X.', [2] => '...' ) When this is what you want: array ( [0] => array ( [0] => '.', [1] => '.', [2] => '.' ), [1] => array ( [0] => '.', [1] => 'X', [2] => '.' ), [2] => array ( [0] => '.', [1] => '.', [2] => '.' ) ) SOLUTION: When constructing your 2D array, make sure you explicitly declare each entry in board as an array. So to construct it, your code might look something like this: board = new Array(); rows = 3; for (var i = 0; i < rows; i++) board[i] = new Array('.', '.', '.');
An other way to create a 2D array in javascript is to use Array.from function var 2Darr = Array.from(Array(5), () => { return new Array(5).fill(0) }) This will create a 5 x 5 array completely filled with 0. Array.from takes two parameters, the first one is an javascript iterable Object to extract the array from, the second one is an optional callback where we can specify something to apply to the array elements. Accessing the element can be done simply like in other languages.
I ran into a similar problem. So after reading a lot... this finally suited my needs. myArr = [1,1,1]; var arr = new Array(); for (var i = 0; i < 10; i++) { arr[i] = Array.from(myArr); } //lets edit 3 positions arr[0][1]= -1; arr[3][2]= 100; arr[8][0] = 8080; for(var i=0; i<10; i++){ console.log(i + " === " + arr[i]); } OUTPUT: if you noticed only the edited index values changed... nothing else 0 === 1,-1,1 <--- 1 === 1,1,1 2 === 1,1,1 3 === 1,1,100 <--- 4 === 1,1,1 5 === 1,1,1 6 === 1,1,1 7 === 1,1,1 8 === 8080,1,1 <--- 9 === 1,1,1
Two remarks here: Arrays start with index 0 in every dimension. If you access a string as a 2D array, every element is a char rather than a string. So if you write board[0][0] = 'X'; then you get the right behavior (and that changes the first character of the string, not the second).
The situation and solution given above is pretty simple. The issue of updating specific values in a list of objects (often referred to as an array, but that's a discussion for a different time) has more practical and industrial application. The problem you tend to run into is thinking that looking at a value in a specific cell, e.g. my_array[0][0] returns 'some value' will also let you change that value through an assignment e.g. my_array[0][0] = 'new value'. You will find that depending on how you defined your array, the change shows in the same row across the columns, not what you are needing. Look at the example code as an illustration of creating, and managing a multidimensional list of objects (array). <html> <head> <title>JavaScript Object List/Array</title> <script> //Make a JavaScript array that can manage data of inventory between different locations over time. var list_of_brands = ["BMW","Harley Davidson","Honda","Kawasaki"]; var list_of_locations = ["Dayton","Cincinnati"]; //a month of data var DAYS_IN_A_MONTH = 30; var calendar = []; for(day_of_sales = 1; day_of_sales <= DAYS_IN_A_MONTH; day_of_sales++){ //hold your locations var shop_location = [];//You need to create a new array for each day - that's part of the trick! for(location_index = 0;location_index < list_of_locations.length;location_index++){ //set up some starting inventory var inventory = [];//You need to create a new array for each location - that's part of the trick! for(brand_index = 0; brand_index < list_of_brands.length; brand_index++){ inventory[list_of_brands[brand_index]] = {"brand": list_of_brands[brand_index], "on_hand": 10,"sold": 0}; };//end inventory loop shop_location[list_of_locations[location_index]] = {"city":list_of_locations[location_index],inventory}; }//end location loop calendar[day_of_sales] = {"Day": day_of_sales, shop_location}; }//end calendar loop //check your work console.log('calendar:'); console.log(calendar); console.log('shop_location:'); console.log(shop_location); console.log('specific information: '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand);//returns 'BMW' console.log('change Dayton.BMW information: '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand="Triumph");//change value console.log('check work (Dayton.BMW): '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand);//check work - PASS console.log('check work (Cincinnati.BMW): '); console.log(calendar[1].shop_location["Cincinnati"].inventory["BMW"].brand);//check work other location - PASS!! //Make some lasting and specific changes console.log("Now make a change in the month's value over showing a sale on the 13th"); var sale_date = 13; console.log("date of sale " + sale_date + "th"); var original_number_on_hand = calendar[sale_date].shop_location["Dayton"].inventory["BMW"].on_hand; console.log("original_number_on_hand on that date: " + original_number_on_hand); var number_of_units_sold = 3; console.log("number_of_units_sold on that date: " + number_of_units_sold); var new_inventory_level = original_number_on_hand - number_of_units_sold; console.log("new_inventory_level: " + new_inventory_level); for(date_index = sale_date; date_index <= DAYS_IN_A_MONTH; date_index ++){ calendar[date_index].shop_location["Dayton"].inventory["BMW"].sold = number_of_units_sold; calendar[date_index].shop_location["Dayton"].inventory["BMW"].on_hand = new_inventory_level; } console.log("Show change in inventory"); console.log(list_of_locations[0]+" has " + calendar[10].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[10].shop_location["Cincinnati"].inventory["BMW"].on_hand); console.log(list_of_locations[0]+" has " + calendar[11].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[11].shop_location["Cincinnati"].inventory["BMW"].on_hand); console.log(list_of_locations[0]+" has " + calendar[12].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[12].shop_location["Cincinnati"].inventory["BMW"].on_hand); console.log(list_of_locations[0]+" has " + calendar[13].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[13].shop_location["Cincinnati"].inventory["BMW"].on_hand); console.log(list_of_locations[0]+" has " + calendar[14].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[14].shop_location["Cincinnati"].inventory["BMW"].on_hand); console.log(list_of_locations[0]+" has " + calendar[15].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[15].shop_location["Cincinnati"].inventory["BMW"].on_hand); console.log(list_of_locations[0]+" has " + calendar[16].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[16].shop_location["Cincinnati"].inventory["BMW"].on_hand); //add new items to a shop's inventory var inventory_2 =[]; for(brand_index = 0; brand_index < list_of_brands.length; brand_index++){ inventory_2[list_of_brands[brand_index]] = {"brand": list_of_brands[brand_index], "on_hand": 10,"sold": 0}; };//end inventory loop console.log("show inventory_2");console.log(inventory_2); console.log("add inventory");inventory_2["Indian"] = {"brand": "Indian", "on_hand": 10,"sold": 0}; console.log("show updated inventory_2");console.log(inventory_2); </script> </head> <body> <p>look in the JavaScript console for output</p> </body> </html>