Array appending after each onclick and loop in javascript - javascript

This is the code fragment I have tried:
radio.onclick = function() {
var pp = e.target.result.split("\n");
var pq = pp.split('\n');
var pr = []; // array to append each values
for (var k = 0; k < pq.length; k++) {
var a = pq[0];
}
pr = a; // I need to create an array which should append again and again
}
In this code, after clicking a radio, a loop generates the value for the 'a' variable, whom it's added to array 'pr'. I want to add the generated value to 'pr' itself after the next on-click.
Is it possible?

Just define the array
pr
globally.
var pr = []; // array to append each values
radio.onclick = function() {
var pq = pp.split('\n');
for (var k = 0; k < pq.length; k++) {
var a = pq[0];
}
pr.push(a); // i need to create an array which should append again and again
}
But there you just get the last pq[0]of the loop
Hope that helps

You probably want to do this:
radio.onclick = function() {
var pq = pp.split('\n');
var pr = []; // array to append each values
for (var k = 0; k < pq.length; k++) {
pr.push(pq[k]);
}
}
If you need global access to pr just define it outside from radio.onclick.
Edit
even shorter:
radio.onclick = function() {
var pq = pp.split('\n');
}
or global
var pq = [];
radio.onclick = function() {
pq = pp.split('\n');
}

$(document).ready(function(){var array = new Array(); //Global declaration
radio.onclick = function(){
//do stuff here..
//get your value
array.push(your value);
}
});
//if you want to clear the array
array.splice();

Related

How to loop over an array of objects using javascript?

I'm trying to loop an array that contains objects and I keep getting and error: "Cannot set property 'color' of undefined". What am I doing wrong?
var ObjectTest = function(something1, something2){
this.Name = something1;
this.Job = something2;
this.color = '';
this.numbers = [];
}
var first = new ObjectTest('Paul', 'teacher');
var second = new ObjectTest('Jane', 'doctor');
var third = new ObjectTest('Mike', 'student');
var someArray = [];
someArray.push(first, second, third);
console.log(someArray);
for(var i =0; i <= someArray.length; i++){
someArray[i].color = 'red';
};
You need to iterate until the length of the array but not over, because indices are zero based
for (var i = 0; i < someArray.length; i++) {
// ^
An array returns undefined for a not existing item. undefined has no property to assign a new value.
var ObjectTest = function(something1, something2) {
this.Name = something1;
this.Job = something2;
this.color = '';
this.numbers = [];
};
var first = new ObjectTest('Paul', 'teacher');
var second = new ObjectTest('Jane', 'doctor');
var third = new ObjectTest('Mike', 'student');
var someArray = [];
someArray.push(first, second, third);
for (var i = 0; i < someArray.length; i++) {
someArray[i].color = 'red';
} // no semicolon here
console.log(someArray);
<= was rong
var ObjectTest = function(something1, something2){
this.Name = something1;
this.Job = something2;
this.color = '';
this.numbers = [];
}
var first = new ObjectTest('Paul', 'teacher');
var second = new ObjectTest('Jane', 'doctor');
var third = new ObjectTest('Mike', 'student');
var someArray = [];
someArray.push(first, second, third);
for(var i =0; i < someArray.length; i++){
someArray[i].color = 'red';
};
console.log(someArray);
Replace <= to < in your loop.
There's only 3 items on the array, meaning you have indexes 0, 1 and 2. The loop should stop when it arrives at at 3. But since you used <= and not <, i <= 3 when i is 3 is true thus executing the code. The error is caused by someArray[3] not existing.
A safer way to loop through arrays without dealing with indexes is to use array.forEach. It only loops as many times as there are items in the array.
someArray.forEach((object, index) => {
object.color = 'red'
})
An easier way to go over an array is to use the forEach.
Something like this:
someArray.forEach(data => data.color = 'red');

For loop prints only last value array in javascript

for (var i = 0; i < featureSet.features.length; i++) {
for (var f = 0, f1 = featureTracts.length; f < f1; f++) {
rows["Sensor"] = featureTracts[f].attributes.Sensor;
rows["Resolution"] = featureTracts[f].attributes.Resolution;
rows["Dtofparse"] = featureTracts[f].attributes.Dtofparse;//PATH_ROW
// alert(rows);
}
resosat1[i] = rows;
}
i am trying to print all values in resosat1[i] array but it will take only last value and all values overwirite and update only last value to array
for (var i = 0; i < featureSet.features.length; i++) {
var rowAaaray = [];
for (var f = 0, f1 = featureTracts.length; f < f1; f++) {
var rows = {};
rows["Sensor"] = featureTracts[f].attributes.Sensor;
rows["Resolution"] = featureTracts[f].attributes.Resolution;
rows["Dtofparse"] = featureTracts[f].attributes.Dtofparse;//PATH_ROW
// alert(rows);
rowAaaray.push(rows);
}
resosat1[i] = rowAaaray;
}
}
Because you are maintaining one variable and overriding it in loop. So you will get last overwritten object only.
I agree with the guy in the comment. Try:
for (var i = 0; i < featureSet.features.length; i++) {
for (var f = 0, f1 = featureTracts.length; f < f1; f++) {
rows["Sensor"] = featureTracts[f].attributes.Sensor;
rows["Resolution"] = featureTracts[f].attributes.Resolution;
rows["Dtofparse"] = featureTracts[f].attributes.Dtofparse;//PATH_ROW
resosat1[f] = rows; <======== THIS WILL STORE THE VALUE OF EACH ROW CREATED
}
<==//TRY STORING THE resosat1 array In another array here instead.
//eg. arrayEx[i]=resosat1
//Alternatively, you could use a 2D Array eg. arrayEx[i][f]
}
Hope this helps you out.
try this one..
for (var i = 0; i < featureSet.features.length; i++) {
var arr = []; // create array
for (var f = 0, f1 = featureTracts.length; f < f1; f++) {
var rows = {};
rows["Sensor"] = featureTracts[f].attributes.Sensor;
rows["Resolution"] = featureTracts[f].attributes.Resolution;
rows["Dtofparse"] = featureTracts[f].attributes.Dtofparse;//PATH_ROW
// alert(rows);
arr.push(rows);
}
resosat1[i] = arr;
}
}
rows is undeclared (at least in your snippet).
On the other hand, putting var rows = {}, as some suggest, will fix your problem because it creates new object each time. But, if your javascript version accepts it, it would be better to declare it wit let because, this way, you will be really creating new fresh variable (in block scope).
Declaring rows in an outer block will not fix your problem because you will be assigning same object during the whole loop.

javascript object reference by array

How can I refer to an object element dynamically during a loop by using an array, something like this:
var obj = {};
var lvl = ['x','y','z'];
var ol = [];
for (var l in lvl){
ol.push( lvl[l] )
obj[ol] = 'someval'
}
so where the reference may be obj[x][y][z] so each time the loop iterates, an additional key reference is appended, but I do not know how many levels there will be.
Not sure if I have explained that very well ?!
Based on how you answered my comment I believe this code will provide the nested object structure you are looking for.
var obj = {};
var lvl = ['x','y','z'];
var ol = {};
for (var i = 0; i < lvl.length; i++){
obj[i] = {};
ol = obj[key];
}
You mean you want someval to be the value of obj.x.y.z? You can always refer to the newly created levels using a variable:
var obj = {};
var levels = ['x','y','z'];
var pointer = obj;
for (var l=0; l<levels.length; l++) {
key = levels[l];
if (l < levels.length-1) { // if not last element
pointer[key] = {};
pointer = pointer[key];
}
else { // if last element
pointer[key] = 'someval';
}
}
console.log(obj); // should log {x:{y:{z:"someval"}}}

Copying array of objects into another array is it reference type in JQuery

I have a array of objects TransactionVModel.FiltersList[].
When I copy this array to another array fltrList[] and if I modify any of the object in array fltrList will it get reflect in Array TransactionVModel.FiltersList in JQuery ? For better clarity below is my example. As per me since it is a reference type it should update array TransactionVModel.FiltersList as well but in my scenario it is not happening, can I know why it is not happening ?
TransactionVModel.FiltersList is declared as ko.observableArray(); in my code.
function UpdateSelectedFilters(data) {
var fltrList = [];
fltrList = TransactionVModel.FiltersList();
for (var i = 0; i < data.length ; i++) {
var index = fltrList.indexOf(data[i]);
if (index != -1) {
var fltrObj = fltrList[index];
var fltrValArr = [];
fltrValArr = data.valueItems;
for (var j = 0; j < fltrValArr.length; j++) {
if (fltrValArr[j].IsSelected == true) {
if (fltrObj.indexOf(fltrValArr[j]) != -1) {
var selectedVal = fltrObj[fltrObj.indexOf(fltrValArr[j])];
selectedVal.IsSelected = true;
}
}
}
}
}
In my scenario I am updating selectedVal.IsSelected property but it is not reflecting the observableArray TransactionVModel.FiltersList.
You need to tell knockout that your array has changed with valueHasMutated:
function UpdateSelectedFilters(data) {
var fltrList = [];
fltrList = TransactionVModel.FiltersList();
//...
TransactionVModel.FiltersList.valueHasMutated();
}

How do i make it simple?

The following code is finding the largest number and if exist any value then i want to add it with one why i need this i want to store unique value
var xmlDoc=xmlHttpRequest.responseXML;
var recordSet = xmlDoc.getElementsByTagName("RECORD");
for(var j=0;j<recordSet.length;j++)
{
expNbrVal[j] = recordSet[j].getElementsByTagName("COL")[0].firstChild.data;
}
largest = expNbrVal[0];
for(var jc=1;jc<expNbrVal.length;jc++)
{
if(parseInt(expNbrVal[jc])>parseInt(largest))
{
largest = expNbrVal[jc];
}
}
if(recordSet.length>0)
{
var expval = parseInt(largest);
document.getElementById("expenseNbr").value = expval+1;
}
else
{
document.getElementById("expenseNbr").value =1;
}
expNbrVal.length =0;
I don't know the original code and you are using some already existing values so i don't know if this works, But this is what I would make from it.
Array.max = function( array ){
return Math.max.apply( Math, array );
};
var array = [];
var xmlDoc=xmlHttpRequest.responseXML;
var recordSet = xmlDoc.getElementsByTagName("RECORD");
if(recordSet.length>0) {
for(var j=0; j<recordSet.length; j++) {
array.push(parseInt(recordSet[j].getElementsByTagName("COL")[0].firstChild.data));
}
var largest = Array.max(array);
}else{
var largest = 0;
}
document.getElementById("expenseNbr").value = largest + 1;

Categories

Resources