I can't understand this code. Before entering into the body:
I cant upload text with English. I definitely see array declaration myArray = new Array(); but suddenly I see myArray[i]= new array();. Another I see myArray[i][j]
What's happening?
i know that
if i want using method array
i can use myArray = new array(5);
AND
i know that "my Array " = new array();
" " this part just function only name
not using another function
but this code means 'you are wrong'
i need that this part need understanding
PS. thanks for editing and answering:)
i see those
so i need to edit
and i want see former writing
myArray is an array of arrays. Each i element of myArray[i] is an array itself. You can picture it as a 2-d grid, like a cheessboard (8x8 squares):
myArray[0][0] myArray[0][1] ... myArray[0][7]
myArray[1][0] myArray[1][1] ... myArray[1][7]
. .
. .
. .
myArray[7][0] myArray[7][1] ... myArray[7][7]
Your code is building an HTML table using a two-dimensional array.
myArray = new Array(); creates the first array. In the while loop, you are building the first dimension of the array when setting a value to myArray[i]. By calling myArray[i] = new array();, you are making that value another array.
The first while loop is going to create as many rows of those 5 values in titleArray as long as you keep confirming. The second of code after that is building an HTML table with a default 1st followed by as many as you confirmed in the first loop, and each will be composed of 5 .
Hope this helps!
Related
I missing something when trying to push to an array while preventing duplicates.
I keep figuring out code that will push every occurence of an employee to the new employees array but I cannot figure out how to only push an unique list.
My final array is a 2d array so that can be setValues() back into a column in the Google sheet.
function queryEmployees(){
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var lRow = sh.getLastRow();
var data = sh.getRange(1,1,lRow,2).getValues();
var employees = [];
for(i=0;i<data.length;i++){
if(data[i][0]==='Team member evaluated'){
if(employees.indexOf([data[i][1]])===-1){
employees.push([data[i][1]]);
}
}
}
Logger.log(employees);
Logger.log(employees.length);
SpreadsheetApp.getActiveSpreadsheet().getSheets()[1]
.getRange(1,1,employees.length,1).setValues(employees);
}
IndexOf does not work with objects in arrays without your rewriting the function or writing your own. It works fine with strings, though. So a simple fix is to create a parallel array of strings, which allows us to keep your code almost intact. Thus, add,
var employeesIndex=[];
after your
var employees=[]
change the condition on your inner "if" clause to
(employeesIndex.indexOf(data[i][1])===-1)
and within that if block add a line to update the index
employeesIndex.push(data[i][1]);
That way the index tracks duplicates for you while your employees array contains arrays like you need.
I send a php array like:
$var = array (
0=> 4,
1=> 6,
2=> 8,
...
as json_encode($var); into the uri and then I receive it into javascript file is still ok here but when I push it into new array like this :
this.patg.push(attd);
Is inserted like this below .
var attds = ["4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606"]
I know I have to find the problem. but
Questions:
could you please tell me why this could happends or help me to deal with it.
but in any case just for knowledge . how you would add the extra " " surrounding the , that i miss to be an array , or is that crazy idea to fix this?
If you are receiving a string value and you want to use it as an array of integers you should split it into an array first:
var receivedData = "4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606";
var dataArray = receivedData.split(",");
Afterwards you can use it with another array, however be aware that if you already have a defined array into which you want to push the dataArray you shouldn't push but concat instead.
In other words if you have:
var previousArray = [1,2,3];
previousArray.push(dataArray);
You will get
[1,2,3,[4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606]]
meaning that the whole array is pushed onto the 4th position of previousArray.
If, on the other hand, you concat the arrays will merge:
var previousArray = [1,2,3];
previousArray.concat(dataArray);
[1,2,3,4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606]
Source: http://www.w3schools.com/jsref/jsref_concat_array.asp
I am storing some values in array like this.
var test = [];
I am pushing the values to this array as test.push(sample);
I have some logic for calculating this value
var sample= (a/b.length)*100;
When I click on a button, the above logic for calculating value of sample is done and once I got the value of sample I am pushing it to test[] array. Now I want to retrieve all the values from the test[] array whenever I check the checkbox. I am able to do all this but I am facing a problem here. only the last pushed value is saving. but I want to save all the values that are being pushed. can anyone please help me in solving this issue.
Quick response is needed and appreciated
Regards
Hema
You need to use 2 dimensional array for this.
Use
var test= new Array();
then assign value test['someKey']=sample;
or test.push(sample); . you can retrieve array value like alert(test[0]) or by iterating array with $.each(test,function(index,value){alert(value)});
What you want to do is create an Array which would function as a list of value sets.
You would then be able to push all the changes into an array, and put it in the list.
for instance:
var mainList = new Array();
var changeListA = new Array();
var changeListB = new Array();
// do some stuff on change list **a** .. push(something)
changeListA .push(something);
changeListA .push(something);
changeListA .push(something);
// do some stuff on change list **b** .. push(something)
changeListB .push(changeListB);
mainList.push(changeListA);
Your question is not perfectly clear to me, however I can at least provide a small jsFiddle that proves to you that (how) array.push works.
Other answers indicate that what you want is either a two dimensional array, or a "hashmap" or "associative array" where the array values are stored using a key name. The code here can be used in the fiddle to achieve either or...
http://jsfiddle.net/xN3uL/1/
// First if you need 2 dimensional arrays:
myArray.push( ["Orange", "Apple"] );
myArray.push( ["Mango", "Pineapple"] );
// Secondly, if you need hashmap or associative array:
var myObj = {};
myObj['key'] = 'value';
alert(myObject.key);
I have really done what I think is a not-code-review-passing hack to pass a 2-dimensional array from PHP to Javascript. The outer array has elements, and each of its elements is an array.
Each inner array consists of 4 fields from my database records. The inner array elements are: the name of a town, its latitude and its longitude, and an integer index.
Is the code working? Yes. But I'm hating the fact that I am 99% convinced that, as a fairly raw beginner, there is a much better way to create then pass a 2d array from PHP to Javascript and I need to know how, as I hacked this together through trial-and-error and reading lots of SO posts, and did not create this from a priori know-how, wisdom or confidence.
Each outer array element is an array that (needs to) look like this:
top
array:
[0] = ["Campbell", 37.21, 122.0, 0]
[1] = ["Sunnyvale", 37.54, 121.37, 1]
[2] = ["Saratoga", 37.24, 122.001, 2]
[3] = ......etc. etc...........
Note that the 2nd level arrays have a string, then a float, then another float, then an integer.
Here's the code in PHP that packages my database records into a 2-d PHP array (error checking, other code is not shown, for clarity):
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
$outerArray = array();
for($i = 0; $i < $numrows; $i++)
{
$theRow = mysql_fetch_row($result);
$city = $theRow[1];
$lat = $theRow[22];
$lng = $theRow[23];
$outerArray[] = array($city, $lat, $lng, $i);
}
$latLngValues = json_encode($outerArray);
// EDIT: ADDED TO TELL ME WHAT THIS 2d ARRAY ACTUALLY LOOKS LIKE
var_dump($latLngValues);
In the onload handler for my web page, I call a javascript function and pass this array:
<body onload='handleLoad(<?php echo $latLngValues ?>)'>
Here is my handleLoad():
function handleLoad( latLng2dArray )
{
for (var i = 0; i < latLng2dArray.length; i++)
{
var town = latLng2dArray[i];
var latitude = Number(town[1]);
var longitude = Number(town[2]);
// I USE THE DATABASE RECORD'S NUMBERS TO CREATE A Gmaps LatLng
var myLatLng = new google.maps.LatLng(latitude, longitude);
}
There's probably a cleaner, and/or more efficient, way to do this.
For example, I found that if I did not use the Number() function to 'force' my database numbers into a number, the call to "new google.maps.LatLng(latitude, longitude)" was giving me NaN.
So I'm hoping more experienced people can let me know a cleaner way. While this code works, I hacked at it for a day through trial and error.
EDIT: I used a var_dump() in my php code to see what the 2d array "$latLngValues" looks like just before it's passed to my onload handler, and "$latLngValues" looks like this:
string(133) "[["Campbell","37.2724","-122",0],["Sunnyvale","37.2724","-122",1],["LosGatos","37.2607","-122",2],["Saratoga","37.2607","-122.046",3]]"
I want to point out this: in my database, the data type I used is 'float' for the latitude and longitude. Not sure how/why the var_dump shows them as a string (not floats) while the integer index is treated correctly, and not a string.
No one offered a better coding strategy so for now, I'm going with the existing code above -- it aint pretty but it works. I'll post back if a more-correct way is found.
I have a web form with two drop-down boxes, and I'm looking for a way to dynamically update the options of the second box based on selections from the first.
The first box represents a data type, and the second box is a list of databases associated with the selected type.
I have the basic code running smoothly here:
var TypeA_DbSuffixList = ['Test1', 'Test2', 'Test3'];
var TypeB_DbSuffixList = ['TestA', 'TestB', 'TestC'];
function fill_dbSuffixList(){
document.getElementById("dbSuffixList").options.length = 0;
var suffixMenu = document.getElementById("dbSuffixList");
var dataFormat = document.getElementById("dataFormatType");
var suffixList = dataFormat.value + "dbSuffixList";
if (suffixList == 'TypeA_dbSuffixList') {
for(index in TypeA_dbSuffixList) {
suffixMenu.options[suffixMenu.options.length] = new Option(TypeA_dbSuffixList[index], index);
}
}
if (suffixList == 'TypeB_dbSuffixList') {
for(index in TypeB_dbSuffixList) {
suffixMenu.options[suffixMenu.options.length] = new Option(TypeB_dbSuffixList[index], index);
}
}
}
That code (activated whenever a selection is made in the dataType box) clears the existing list of options and repopulates the list based on the selected value of the "dataFormatType" box.
The problem that I face is that the actual lists of database tables are not hard coded and are instead generated with the following calls to the server to avoid repetitive editing of the page every time a new database is added:
var TypeA_dbSuffixList = ${TypeA_dbSuffixList};
var TypeB_dbSuffixList = ${TypeB_dbSuffixList};
These calls return the following code:
var TypeA_dbSuffixList = [Test1, Test2, Test3];
var TypeB_dbSuffixList = [TestA, TestB, TestC];
With the above code, the initial function treats each entry in the type arrays as an undefined variable, and nothing is ever written to the drop-down list.
If I were to add
var Test1 = "Apple";
var Test2 = "Orange";
var Test3 = "Grape";
prior to the "for" loop for TypeA, then selecting TypeA from the dataType drop-down list returns "Apple", "Orange", and "Grape" as the available databases for TypeA.
Visually, I see what needs to be changed. The [Test1, Test2, Test3] returns need to be ['Test1', 'Test2', 'Test3']. I'm just unsure exactly how to go about changing it, and have exhausted every web search I can think of.
Is there a way to either change the format of the returned arrays, or use the existing format and pass variable names as drop-down selections instead of using variable values?
Any help is greatly appreciated. I will continue to search for an answer on my own as well and will post it here should I find one.
I think the cleanest solution would be to change the code on the server-side to generate a proper JavaScript array of Strings, with the values enclosed in single or double quotes.
If that's not possible for some reason, and you want a pure-JavaScript solution, then I suggest you wrap the entire JSP/ASP/PHP variable (not sure what framework you're using) in double quotes, strip the string of brackets and spaces using a regex, and then split it into a string array using the comma as a delimiter.
So in your JavaScript, this:
var TypeA_dbSuffixList = ${TypeA_dbSuffixList};
would become this:
var TypeA_dbSuffixList = "${TypeA_dbSuffixList}".replace(/[\[\]\s]/g,"").split(",");
I think the best way to convert data in a server side language into something to be used in JavaScript is to JSON encode your objects.
I'm not sure what language your using on the server, but in PHP you can do the following
var arr = <?php echo json_encode( array ('abc', 'def', 'ghi') ); ?> ;
And your output will be
var arr = ['abc', 'def', 'ghi'] ;
This will make sure that strings with embedded new lines, tabs, quotes are properly escaped.
JSP
You said you're using JSP but the code you have looks more like velocity or free marker inside JSP. In JSP you could use the following, provided you download Gson
var TypeA_dbSuffixList = <%= new Gson().toJson(TypeA_dbSuffixList) %>;