I have a multidimensional array in which some values are present i
want to retrieve the [0][1] or [1][1] index value. I am getting
undefined as array, if i tried to directly try to get the array value
am able to get the value.
This what i want to achieve
I had a select drop down menu , According to the selected index i
need to retrieve a message from the array box. For say if the index is
1 then i had to get [1][1] array index value if it is zero then [0][1]
array index value
This is the fiddle what i have done. http://jsfiddle.net/hTQZ9/
see this update: http://jsfiddle.net/hTQZ9/1/
var MessagesObj = {
testName: []
}
MessagesObj["testName"].push(["testName_custom_message_Label1val","Custom message for label 1"]);
MessagesObj["testName"].push(["testName_custom_message_Label2val","Custom message for label 2"]);
alert(MessagesObj["testName"][1][1]);
var classChk = $(".customCheckEnabled").get(0);
var getClassindex = classChk.selectedIndex;
var getVarName = classChk.id
var getCstMsgName = MessagesObj[getVarName];
alert(getCstMsgName);
var getMessage = getCstMsgName[getClassindex][1];
alert(getMessage);
getCstMsgName is a string, not an array.
One way is to use this
$(document).ready(function () {
var testName_MessagesArray = new Array();
var cntr = 0;
testName_MessagesArray[cntr] = new Array("testName_custom_message_Label1val", "Custom message for label 1");
cntr++;
testName_MessagesArray[cntr] = new Array("testName_custom_message_Label2val", "Custom message for label 2");
cntr++;
alert(testName_MessagesArray[1][1]);
var classChk = $(".customCheckEnabled");
alert(classChk);
this.testName = testName_MessagesArray; //<-- set this with the name
var getClassindex = classChk.attr("selectedIndex");
alert(getClassindex);
var getVarName = classChk.attr("id");
alert(getVarName);
var getCstMsgName = this[getVarName]; //<-- reference it from this
alert(getCstMsgName);
var getMessage = getCstMsgName[getClassindex][1];
alert(getMessage);
});
If testName_MessagesArray is in global scope, you can do window["testName_MessagesArray"] to reference it. Your current example is local scope so that would not work.
You should really use an array literal instead of, er, cntrs:
var testName_MessagesArray = [
["testName_custom_message_Label1val", "Custom message for label 1"],
["testName_custom_message_Label2val", "Custom message for label 2"]
];
Then, if you want to retrieve a value from it, use testName_MessagesArray[x][y].
What you were doing:
var classChk=$(".customCheckEnabled");
// this is a jQuery element, alerted as [object Object]
var getClassindex=classChk.attr("selectedIndex");
// this is 0 or 1
var getVarName=classChk.attr("id");
// this will be the id of the first selected element, a string
var getCstMsgName=getVarName+"_MessagesArray".toString();
// this will create a string, from the "getVarName"-string and your string-literal-toString
var getMessage=getCstMsgName[getClassindex][1];
// as "getCstMsgName" is a string - not the twodimensional array,
// getCstMsgName[getClassindex] returns the character at the selected index (as a string)
// and getCstMsgName[getClassindex][1] results in the second character of the one-character-string - undefined
Related
I am writing a for loop that is iterating over an array which contains different lines in a text document.
Each iteration I am trying to pull certain parts of each of the text data lines and add them to an object, namely localinoData.
At the end of each iteration I am trying to add the localinoData object (with each object property set to a new one) to a new array.
When just adding the string found in each line the to data array (localinoDataObjArray) I get different values for each of the array. However when I now change the localinoData object properties on each iterations and try to append that changed object to the array, i get the same object in all of the array positions, e.g when I
alert(localinoDataObjArray[x].X_COORD);
for all values of x, the X_COORD is the same.
function GetlocalinoDataFromFile(localinoDataFile){
var localinoDataObjArray = new Array();
var localinoData = {
time: null,
tagID: null,
X_COORD: null,
Y_COORD: null,
Z_COORD: null,
};
var allData = localinoDataFile.responseText;
var arrayOfDataLines = allData.split('\n');
// for each iteration, get the tagID, and the co-ords(seperate) and then
// create a localinoData object and add to array
for (var i = 0; i < arrayOfDataLines.length; i++) {
if (/tag: [0-9]{22}/.test(arrayOfDataLines[i])) {
var tagID = /tag: [0-9]{22}/.exec(arrayOfDataLines[i]);
localinoData.tagID = tagID;
}
if (/[0-9]+.[0-9]{3}, [0-9]+.[0-9]{3}, [0-9].[0-9]{3}/.test(arrayOfDataLines[i])) {
XYZ_COORDS = /[0-9]+.[0-9]{3}, [0-9]+.[0-9]{3}, [0-9].[0-9]{3}/.exec(arrayOfDataLines[i]);
temp = XYZ_COORDS.toString();
temp2 = temp.split(', ');
// Here I am changing the object to new values each loop
localinoData.X_COORD = temp2[0];
localinoData.Y_COORD = temp2[1];
localinoData.Z_COORD = temp2[2];
}
// Here I am appending the newly changed object to my array
// however the same object is being added every time
// (which corresponds to the last line in the text document)
localinoDataObjArray.push(localinoData);
}
// the object values for localinoDataObjArray[0]
// and localinoDataObjArray[50] are the exact same
alert(localinoDataObjArray[20].X_COORD);
}
I expect all of the array values to be different corresponding to the different lines in the text document. However all of the array values are the same (which equal the expected result of iteration over the last line in the text document).
I am very confused as when i = 0, it should be adding an object that has the values of the first line in my text document, however it shows the values i would expect from the last line in the document.
This is very strange to me and seems like a looping problem? I am very confused and would appreciate any help in this matter.
They are all references to the same object which you keep overwriting.
Try and make a fresh instance of localinoData in every iteration of your for loop.
function GetlocalinoDataFromFile(localinoDataFile){
var localinoDataObjArray = new Array();
var allData = localinoDataFile.responseText;
var arrayOfDataLines = allData.split('\n');
// alert(arrayOfDataLines[4]);
// for each iteration, get the tagID, and the co-ords(seperate) and then create a localinoData object and add to array
for (var i = 0; i < arrayOfDataLines.length; i++) {
var localinoData = {
time: null,
tagID: null,
X_COORD: null,
Y_COORD: null,
Z_COORD: null,
};
if (/tag: [0-9]{22}/.test(arrayOfDataLines[i])) {
var tagID = /tag: [0-9]{22}/.exec(arrayOfDataLines[i]);
localinoData.tagID = tagID;
}
if (/[0-9]+.[0-9]{3}, [0-9]+.[0-9]{3}, [0-9].[0-9]{3}/.test(arrayOfDataLines[i])) {
XYZ_COORDS = /[0-9]+.[0-9]{3}, [0-9]+.[0-9]{3}, [0-9].[0-9]{3}/.exec(arrayOfDataLines[i]);
temp = XYZ_COORDS.toString();
temp2 = temp.split(', ');
localinoData.X_COORD = temp2[0];
localinoData.Y_COORD = temp2[1];
localinoData.Z_COORD = temp2[2];
}
localinoDataObjArray.push(localinoData);
}
alert(localinoDataObjArray[20].X_COORD);
}
If i try to add more keys with values to a javascript object it alters the value of all keys, not just the one I have added.
var corridorObject = {};
var makeObjects = [];
function someFunction(){
var a = makePoints;
var Corridor = viewer.entities.add({
corridor : {
positions : (a),
width : 10.0,
material : Cesium.Color.GREEN,
}
var idv0 = Corridor.id
corridorObject[idv0] = makeObjects;
console.log(corridorObject);
makeObjects.length=0;
}
The Corridor ID is a guid, the makeObjects an array of objects, when I run this it adds the key perfectly, and the values, but when I run it a second time it adds a new key with the new ID and new values, but it also changes the values for all the other keys to the most recent values.
here is the console, as you can see the first time the array for the ID is 3 long the second time with the same id its 2 long
Object {91ff9967-7019-4e76-846e-c0e125481060: Array[3]}
Object {91ff9967-7019-4e76-846e-c0e125481060: Array[2], 3de2c2b1-5fb6-495c-9034-2b37713e5c30: Array[2]}
Sorry to be more clear, this is from Cesiumjs, its taking points and converting them to a corridor, the corridor id and an array of the points that made it are then added to this object. The array of points is then emptied.
If you are repeating
var corridorObject = {};
var makeObjects = [];
var idv0 = Corridor.id
corridorObject[idv0] = makeObjects;
console.log(corridorObject);
These line of code then It will initialise
var corridorObject = {};
Thats why you will get only one key. Put initialization outside of the iteration
I have seen several posts on how to convert a string to an array using .split(), but I am curious how I would have a list re-sort it's self everytime a new string is added.
For example, I have an input box where I enter names in the format of 'First Last'. On the button click event, the input div clears, a dynamic list is generated of the names entered, and it reformats them 'Last, First'.
Every time a new name is entered, the list should resort itself alphabetically.
I would have this output div split itself on a delimiter after each name, so that the list is an indexed array of strings, but I don't have a delimiter to split on.
Here is my code so far. I know there are several things I could do to improve this but I'm looking for a very simple answer to storing these values in an array instead of a list of strings just so that they can be sorted alphabetically.
Assume all data will be entered in the format 'First Last' including capitalization.
The comment in all caps involves the 'combine' variable that needs to become an array.
var namesArr = [];//create an empty array that will hold the names
var output = document.getElementById('output');//get the output element (text area).
var name = document.getElementById('name');//get the textbox
function init(){
var nameBtn = document.getElementById('addNameBtn');//get the name button element
var clrBtn = document.getElementById('clearBtn');//get the clear button element
nameBtn.onclick = enterName;//set up your events here
clrBtn.onclick = clearNames;//set up your events here
}
function enterName(){
if(document.getElementById('name').value !==""){
var arr = document.getElementById('name').value.split(" ");
var space = ", ";
var firstname = arr[1];
var lastname = arr[0];
var outputA = [];
var combine = outputA+firstname+space+lastname+"\n";
output.value += combine//I NEED THIS OUTPUT VALUE
//TO BE STORED IN AN ARRAY
//EVERY TIME A NEW STRING IS ENTERED
//SO THAT I CAN USE .sort() on the array.
}
else{
alert("Please enter a name in the format 'First Last'");
}
if(document.getElementById('name').value !==""){
document.getElementById('name').value = "";//clear names input
}
}
function clearNames(){
document.getElementById('name').value = "";//clear names input
document.getElementById('output').value = "";//clear output input
}
init();//this will run when after the DOM loads
Thank you so much for any help or feedback.
You can use the .push() function to append the new name to the array and then sort the strings. Using the array that you have defined var namesArr = [];
namesArr.push(newLastFirstName);
namesArr.sort();
Then you can do what you want with the sorted array. (In this case outputting the list to the textarea element.)
Example:
var namesArr = [
"Smith, John",
"Philip, Bill",
"Power, Max",
"Bar, Foo"
];
// Once the name has been converted ("First Last" -> "Last, First")
// Append the name to the names array
namesArr.push("McFly, Marty");
// (Re-)sort the array since the new element has been added
namesArr.sort();
for(var i = 0; i < namesArr.length; i++) {
console.log(namesArr[i]);
}
Outputs:
Bar, Foo
McFly, Marty
Philip, Bill
Power, Max
Smith, John
I am trying to create an array of objects that contain two pieces of information relating to an order:
Product Stock Code
Product Quantity
Currently I am doing it like this:
$(".orderBtn").click(function(event){
//Show the order Box
$(".order-alert").show();
event.preventDefault();
//Create the Array
var productArray = [];
//Get reference to the product clicked
var stockCode = $(this).closest('li').find('.stock_code').html();
//Get reference to the quantity selected
var quantity = $(this).closest('li').find('.order_amount').val();
var key = "stockCode";
var obj = {
'stockCode' : stockCode,
'quantity' : quantity
};
productArray.push(obj);
$.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
console.log(productArray);
if(quantity == 0){
console.log("Quantity must be greater than 0")
}
I would expect that each time the order button is clicked that the new object would be added to the array of existing objects but instead It just outputs the array with 1 object, the object I've just added.
Is there something I am missing?
Move your array declaration outside of the function into the global scope.
What happens in your case is that each time you call the function a new array is created(function scope) and therefore only one result is produced.
Read this about scopes\hoistings.
var productArray = [];
$(".orderBtn").click(function(event){
//Show the order Box
$(".order-alert").show();
event.preventDefault();
//Create the Array
//Get reference to the product clicked
var stockCode = $(this).closest('li').find('.stock_code').html();
//Get reference to the quantity selected
var quantity = $(this).closest('li').find('.order_amount').val();
var key = "stockCode";
var obj = {
'stockCode' : stockCode,
'quantity' : quantity
};
productArray.push(obj);
$.cookie('order_cookie', JSON.stringify(productArray), { expires: 1, path: '/' });
console.log(productArray);
if(quantity == 0){
console.log("Quantity must be greater than 0")
}
declare as global variable
var productArray = [];
$(".orderBtn").click(function(event){
// do here
//productArray.push("anyObject");
});
You are recreating / overwriting the productArray every time the button is clicked. Try moving the var productArray = [] to outside of the click handler
Not so, because your
var productArray = [];
is within the function that sets the cookie, so it's getting defined afresh then having one element added each time the function is called.
You'd need to define productArray outside of the function (as a global variable?) so that it retains its previous value, and new objects are added to it
With var productArray = []; you're declaring a new array on every click. Move that line outside the click handler and the code should start working.
I have a 2 dimension array defined as
var thischart = [[],[]];
and the array contains the following data created programatically:
1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,24,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0
I cannot get the single value of the second field in the particular array cell. For example, if I use the following command to get the value:
alert("thischart[i,1]=" + thischart[0, 1]);
I get the following answer:
thischart[i,1]=2,0
I tried using the second dimension to access the data as
thischart[0][1]);
but it gives me an error message:
I just want to get the second single value in the array such as for array cell 13 I want the value 24 from above. Does anyone have an answer on how to access this array?
I populated the array as follows and then updated it thru program logic:
$hours = [];
for($i = 0; $i< 24; $i++){
$hours[$i] = [];
$hours[$i][0] = ($i + 1);
$hours[$i][1] = "0";
}
And the answer to this question is below:
for(var i in thischart){
var tc = thischart[i];
myvalue = tc[1]); // this is the value I want
}
Thanks to everyone who responded.
For all of them like this:
for(var i in thischart){
var tc = thischart[i];
for(var n in tc){
// n is internal index
// tc[n] is internal value
}
}
For a single value from the first internal Array, the second value:
thischart[0][1];
Why don't you use the console to see what's the return of
thischart[0];
Because it should contain an array. If it does, then
thischart[0][1];
is perfectly valid syntax. And if it doesn't, then
thischart[0,1]
means nothing whatsoever.
Do something like this:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
do you mean something like this:...
http://jsfiddle.net/DSrcz/1/
var arr = [1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0];
arr[33]=1000;
alert(arr[13]);
alert(arr[33]);