I have a addAfter and addBefore function that adds a new element to an array. This array is my storage that other functions use. Basically I am storing low level objects that define table cells. After the element is added to the array I then have to insert the value of the html property of the element the table row.
Is there a way to prototype my array to handle both operations rather than me having to double up on the work load every time I addAfter or addBefore, with-out messing up the prototype of the native array?
var bays=[];
addAfter: function (b, n) {
for (var i = 0, ii, len = bays.length; i < len; i++) {
ii = i + 1; if (ii == n) {
bays.splice(ii, 0, b);
var newCell = canvsTrBay.insertCell(ii);
newCell.outerHTML = b._html;
};
};
this.build();
}
Is it possible to do something like:
bays.prototype.add=function(b,n,isAfter){
for (var i = 0, ii, len = bays.length; i < len; i++) {
ii =(isAfter? (i + 1):(n>0?i-1:0);
if (ii == n) {
bays.splice(ii, 0, b);
var newCell = canvsTrBay.insertCell(ii);
newCell.outerHTML = b._html;
};
};
this.build();
}
You can add it directly to the object itself:
bays.add = ...;
Related
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.
Currently, I'm building an object from an array of objects with the following:
var popOverOptions = {
defaultOption: true
}
if (a) {
options.push({a: "b"});
}
if (c) {
options.push({c: "d"});
}
// Loop through array of objects
for (var i = 0; i < options.length; i++) {
// Add objects in array to popoverOptions object
for (key in options[i]) {
popoverOptions[key] = options[i][key]
}
}
I'm thinking this could be optimized and I'm curious if there is a better way to write this, possibly using .reduce(), .forEach() or some other method.
In ECMAScript 6, you can use
Object.assign to copy the properties to popOverOptions
The spread operator to expand the options array.
Object.assign(popOverOptions, ...options);
You can optimise the loop itself like this:
for (var i=0, n=options.length; i<n; ++i) {
This reduces the number of times you need to access options.length which is slower than reading it from a local.
A smaller optimisation:
for (var i=options.length-1; i--; /* empty */) {
Source: http://www.phpied.com/extreme-javascript-optimization/
You can cache length for a slight speed improvement.
If the keys in your array are identical for each element, you can get twice the speed (in Chrome) by caching Object.keys(options[0]), and iterating through that.
Even if the keys aren't the same, you can still get approx. 25% increase in speed by iterating through Object.keys(options[i]).
var options= [];
for(var i = 0 ; i <= 1000 ; i++) { //create array of objects with random numbers
options[i]= {};
for(var j = 0 ; j <= 5000 ; j++) {
options[i][j]= Math.random();
}
}
var popOverOptions = {};
function keyin() {
var timer= new Date();
for(var i = 0, leni = options.length ; i < leni; i++) {
for(var key in options[i]) {
popOverOptions[key] = options[i][key];
}
}
alert((new Date()-timer)/1000+' seconds');
} //keyin
function objkeys(same) {
var timer= new Date(),
keys= Object.keys(options[0]);
for(var i = 0, leni = options.length ; i < leni; i++) {
if(!same) keys= Object.keys(options[i]);
for(var key = 0, lenk = keys.length ; key < lenk ; key++) {
popOverOptions[keys[key]] = options[i][keys[key]];
}
}
alert((new Date()-timer)/1000+' seconds');
} //objkeys
<button onclick="keyin()">key in options</button><br>
<button onclick="objkeys(true)">Object.keys, same keys per element</button><br>
<button onclick="objkeys(false)">Object.keys, different keys per element</button>
I need to implement DataTable struct ,that is in c#, in javascript.
For example
function Servers(name)
{
this.Name = name;
this.Columns = new Array(5);
var rows = new Array(3);
for (var i=0;i<3;i++)
rows[i]=new Array(5);
this.Rows = rows;
}
I simply access jth element of ith Row by typing like this;
Servers.Rows[i][j]
This works good, but I need to call my object like this;
Servers.Rows[i]["ServerUrl"]
But I dont know how to implement a prototype for this work.
Is there anyway to achieve this?
Note: Columns array holds Column names like in c# and Columns array size always equals to Rows' sub array.
Live demo
function create2Array(d1, d2, fn) {
var arr = [],
d = function(x, y) {},
f = fn || d;
for (var i = 0; i < d1; i++) {
for (var j = 0, curr = []; j < d2; j++) {
curr[j] = f.call(window, i, j);
};
arr[i] = curr;
};
return arr;
};
function createArrayOfObjects(d1) {
var arr = [];
for (var i = 0; i < d1; i++) {
arr[i] = {};
};
return arr;
};
function print2DArray(arr) {
document.body.innerHTML += "<p><b>Array:</b></p>";
for (var i = 0, len = arr.length; i< len; i++) {
document.body.innerHTML += "<p><b>" + i + "</b>: " + arr[i].join(" ") + "</p>";
};
};
function printArrayOfObj(arr) {
document.body.innerHTML += "<p><b>Array:</b></p>";
for (var i = 0, len = arr.length; i< len; i++) {
document.body.innerHTML += "<p><b>" + i + "</b>: " + JSON.stringify(arr[i]) + "</p>";
};
};
var Server = {};
Server.Rows = createArrayOfObjects(10);
Server.Rows[0]["something"] = "test";
printArrayOfObj(Server.Rows);
Use it like this:
Server.rows = create2Array(10, 10);
Or you can even specify a custom init function which takes the index as param.
Say if you want to init your matrix with 0 by default:
Server.rows = create2Array(10, 10, function(x, y) { return 0;});
Or if you use an object.
Server.rows = create2Array(10, 10);
Server.rows[0]["ServerUrl"] = "test";
You should use a hash/object for this.
If you want to refer to variables in a data structure by name/string in javascript the an object is the best option. See here: https://developer.mozilla.org/en/docs/JavaScript/Guide/Working_with_objects
Sorry if this is too basic, but I am struggling at defining 4-dimensional array (of size 6x6x6x6) in JavaScript and initializing it to all 1's. What's the easiest way to do this?
Thanks!
You can use the literal syntax, but it would be very big and cumbersome. You may want to try something like this:
var x = [1, 1, 1, 1, 1, 1];
for (var i = 1; i < 4; i++) {
x = [x, x, x, x, x, x];
}
I found a slightly simpler solution:
var x = 1;
for (var i = 0; i < 4; i++) {
x = [x, x, x, x, x, x];
}
Seems like there should be easier way, but this will do it.
var array = [];
for(var i=0; i<6; i++) {
for(var j=0; j<6; j++) {
for(var k=0; k<6; k++) {
for(var l=0; l<6; l++) {
array[i][j][k][l]=1;
}
}
}
}
Edit
To generate an n-dimensional AxBxCxDx... array (untested):
Array.prototype.fill = function(elem, n) {
for(var i=0; i<n; i++, this.push(elem));
}
function generateArray() {
var dimensions = Array.prototype.slice.call(arguments);
var x = 1;
for (var i = dimensions.length-1; i >= 0; i--) {
x = [].fill(x, dimensions[i]);
}
return x;
}
to generate a 2x3x4x5 matrix:
generateArray(2,3,4,5);
I implemented ddlshack's generalized method, but ran into an issue due to the fact that arrays are "pass by reference" in JavaScript. This resulted in each dimension of the array holding multiple references to the same array rather than copies of it. To correct the issue, I implemented the solution as follows (the only other difference being that I used a second function rather than modify Array's prototype).
var fillArray = function(val, dim) {
var a = [];
for (var i = 0; i < dim; i++) {
if (Object.prototype.toString.call(val) === "[object Array]") {
val = val.slice(0);
}
a.push(val);
}
return a;
};
var generateArray = function() {
var dimensions = Array.prototype.slice.call(arguments),
val = 0;
for (var i = (dimensions.length - 1); i >= 0; i--) {
val = fillArray(val, dimensions[i]);
}
return val;
};
function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed