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.
Related
I have array object like this below
var TTP01[2,0,0,0,0,0,4,6,1,4,0,9,1]
If I assign TTP01[0] like this, I will get Output 2. This is working fine.
But I'm getting values separately and I need to assign the Object.
object = TTP;
count =01;
xy = x*y;
I concat like this below
var obj = objname.concat(count, "[", xy, "]");
console.log( obj );
In console log, I'm getting like this TTP01[0].
But want to get output 2
Please help me... Thanks
This will work.
eval(objname + count)[xy]
fullcode:
var TTP01 = [2,0,0,0,0,0,4,6,1,4,0,9,1];
var objname = "TTP";
var count = "01";
var xy = 0;
console.log(eval(objname + count)[xy]); // 2
You can try like this way,
var TTP01 = [2,0,0,0,0,0,4,6,1,4,0,9,1];
var objname = 'TTP';
var count = '01';
xy = 0;
var obj = window[objname + count];
console.log( obj[xy] );
Assign TTP01 to some base object :
var base = {
TTP01: [2,0,0,0,0,0,4,6,1,4,0,9,1]
}
var objname = 'TTP';
var count = '01';
var objStr = objname + count;
var xy = 0;
console.log(base[objStr][xy])
After an hour googling around I'm utterly confused about how to create & manipulate an associative array (I know it's actually an object) in JS. I'm trying to build an associative array / object as I loop through my page's elements thus:
var array_modules = {};
$('.module').each(function() {
var this_element = $(this);
var module_top = this_element.data('top');
var module_bottom = this_element.data('bottom');
array_modules.push({'top': module_top, 'bottom': module_bottom});
});
And somewhere else I'd like to retrieve the content of my array thus:
for (var index in array_modules) {
var top = array_modules['top'];
var bottom = array_modules['bottom'];
alert('top = ' + top + ' and bottom = ' + bottom);
}
None of this works though. What am I doing wrong?
you can push data into an array only. I hope the below code works for you.
var array_modules = [];
$('.module').each(function() {
var this_element = $(this);
var module_top = this_element.data('top');
var module_bottom = this_element.data('bottom');
array_modules.push({'top': module_top, 'bottom': module_bottom});
});
for (var index in array_modules) {
var top = array_modules[index]['top'];
var bottom = array_modules[index]['bottom'];
alert('top = ' + top + ' and bottom = ' + bottom);
}
This creates a array of associative objects
On your first part of code you are using array_modules as just an array and not associative, just use array_modules = []; On second part you are iterating an associative array but it should be array_modules[index]['top']. Still, by just changing to array just make a forEach loop.
Anyway, this is what I would do :
var array_modules = [];
$('.module').each(function() {
array_modules.push($(this).data());
});
array_modules.forEach(function(data){
console.log(data.top, data.bottom);
})
I have this piece of code in javascript:
var i = 0;
var j = 0;
while (allTextLines.length) {
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
if (i == 0) {
alert(temp);
i++;
}
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
var y = line[3];
var z = line[5];
var g = line[7];
lines[j] = (x + ", " + z + ", " + g);
j++;
}
And it's happening something really weird. When i==0, it alerts temp and its split. After that I'm getting:
Uncaught TypeError: Cannot read property 'split' of undefined
If I remove the if, I will have this error right on the start. But if I do something like this:
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
alert(temp);
var x = (temp[0] + temp[1]+ temp[2] + temp[3] + "-" + temp[4] + temp[5] + temp[6]);
It has no problem splitting (also the alert shows that it has been correctly split). The only problem is that I will have to click "ok" 5600 times. I don't understand what the hell is going on and why I am having this error.
I'm splitting a CSV file with lines like this:
35105,201401,503781827,"8400258","Faro","Lagoa (Algarve)","Portugal"
and I'm trying to add an '-' in here: "8400258", so it becomes "8400-258"
var line = allTextLines.shift().split('"');
var temp = line[1].split('');
Won't that fail when allTextLines only has one element in it, since the array is zero-based? I think you'd need to change the line[x] param to 0:
var temp = line[0].split('');
Might I suggest a different approach?
var line = allTextLines.shift().split(',');
var x = line[3].replace(/^"(\d{4})(\d{3})"$/, "$1-$2");
var y = line[4];
var z = line[5];
var g = line[6];
If you can trust that the format of the data is always the same, it's much less complex to do a pattern based replace than splitting a string like an array and re-assembling it.
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] = {};
/*...*/
}
I am using multi dimension array to store data. It working but when we print it in console it show blank array and under it its showing two array, it should be show only one array inside.
It should look like this.
ar['outbound']['Meal']="111,121"
and its look in console like this
It is printing undefined also and one more thing
how to remove "," from the last
Here is fiddle
Code
var ar = [];
ar['Outbound'] = [];
ar['Inbound'] = [];
var ch="";
var sr= [];
sr['Meal']= [];
sr['Lounge']= [];
$('a').click(function(){
ch = $(this).parent().find('.no').text();
var boundType= $(this).parent().find('.bound').text();
ar[boundType][$(this).parent().find('.service').text()] +=($(this).parent().find('.no').text()) + ","; console.log(ar)
})
To avoid "undefined" you have to set a default value to your array items:
if (!ar[boundType][service]) {
ar[boundType][service] = '';
}
And it's better to add ',' before adding a new value:
if (ar[boundType][service].length > 0) {
ar[boundType][service] += ',';
}
See demo: http://jsfiddle.net/AVU54/1/
The problem is here:
ar[boundType][$(this).parent().find('.service').text()] +=($(this).parent().find('.no').text()) + ",";
Replace that with:
var temp = $(this).parent().find('.service').text();
ar[boundType][temp] = (ar[boundType][temp] + "," || '') + ($(this).parent().find('.no').text());
This checks if the variable exists.
Also, arrays can't have strings as indexes. Use objects, instead:
var ar = {};
ar['Outbound'] = {};
ar['Inbound'] = {};
// etc...