var initialPos = [];
var totalNum = 5;
var dt = 1;
for (var i = 1; i <= totalNum; i++)
{initialPos.push([i*100*Math.random(),i*100*Math.random()])}
var vx = 5;
var vy = 5;
var newPos = [];
var x_Pos;
var y_Pos;
for (var j = 0; j <= totalNum - 1; j++) {
x_Pos = initialPos[j][0] + vx*dt;
y_Pos = initialPos[j][1] + vy*dt;
newPos.push([x_Pos,y_Pos])
initialPos = newPos;
};
console.log(initialPos);
initialPos is an array of ordered pairs. I am trying to create another array called newPos and push some modified elements from initialPos to it, however I keep getting the error that the property of 0 of undefined cannot be read. Any suggestions on to fix this? Thanks in advance!
The issue is in this line initialPos = newPos;
You are assigning initialPos to newPos.
The first time you go through the loop newPos looks something like this [ 27.07844010497107, 137.90462488567533 ]; and you are reassigning initialPos to this value.
The second time you go through the loop when j === 1, initialPos[1] is undefined as you assigned it to newPos that has a length of 1.
I am not sure what you want to do exactly, but isn't it what you need?
var initialPos = [];
var totalNum = 5;
var dt = 1;
for (var i = 1; i <= totalNum; i++)
{initialPos.push([i*100*Math.random(),i*100*Math.random()])}
var vx = 5;
var vy = 5;
console.log(initialPos);
for (var j = 0; j <= totalNum - 1; j++) {
initialPos[j][0] = initialPos[j][0] + vx*dt;
initialPos[j][1] = initialPos[j][1] + vy*dt;
};
console.log(initialPos);
As a side note, I suggest you look at immutability. Here is one article for instance. It would prevent such bugs.
Related
I have some small issue in j query. my code is like this
var tt = 8*1;
var n = tt.toString();
var uu1 = n.split('*');
var count = uu1.length;
var table_id44 = '';
for(k = 0,m = 1; k < count-1; k++,m++)
{
var table_id44[m] = uu1[k];
}
when I put that i got error in console log SyntaxError: missing ; before statement.please someone help.
table_id44 should be declared as an array. and you don't need to redeclare the variable in the for loop.
var tt = 8 * 1;
var n = tt.toString();
var uu1 = n.split('*');
var count = uu1.length;
var table_id44 = [];
for (k = 0, m = 1; k < count - 1; k++, m++) {
table_id44[m] = uu1[k];
}
Try this, You are declaring it as string var table_id44 = ''; and using it as an array.
var tt = "8 * 1";//use it as string so that you can further split it on *
var n = tt.toString();
var uu1 = n.split('*');
var table_id44 = [];
for (k = 0, m = 1; k < count - 1; k++, m++)
{
table_id44[m] = uu1[k];//prevent multiple declaration in loop
}
var divs = [];
for (var x = 0; x <= nodeArray.length; x++) {
for (var q = 0; q <= nodeArray.childElementCount; q++) {
divs[x][q] = nodeArray[x].childNodes[q].childNodes[0]
};
};
I need a two dimensional array of the child of every child of a div for multiple divs.
Can't get it to work ;c
Anyone knows if this is even possible with javascript?
Thanks.
Edit:
Thanks guys, it works now! :D
I ended up doing it like this:
var divs = [];
nodeArray.forEach(function(array, index) {
divs[index] = nodeArray[index].children;
});
var imgs = [];
for (var x = 0; x < divs.length; x++) {
imgs[x] = [];
for (var y = 0; y < divs[x].length; y++) {
imgs[x][y] = divs[x][y].childNodes[0];
}
}
Using your feedback it works now! Really really really thanks! ;D
Arrays are 0-indexed, This means that the last element of an array is not at array.length but at array.length - 1.
You'll have to create a new array (sub-array) and then start adding elements to it.
Your code should be like this:
var divs = [];
for (var x = 0; x < nodeArray.length; x++) {
// here ^^^
divs[x] = []; // create a new sub-array (or divs.push([]);)
for (var q = 0; q < nodeArray.childElementCount; q++) {
// here ^^^
divs[x][q] = nodeArray[x].childNodes[q].childNodes[0];
};
};
var divs = [];
for (var x = 0; x <= nodeArray.length; x++) {
divs[x] = [];
for (var q = 0; q <= nodeArray[x].length; q++) {
divs[x][q] = nodeArray[x][q][0];
};
};
I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});
I have a numeric 2D array (an array of arrays, or a matrix) and I need to do simple matrix operations like adding a value to each row, or multiplying every value by a single number. I have little experience with math operations in JavaScript, so this may be a bone-headed code snippet. It is also very slow, and I need to use it when the number of columns is 10,000 - 30,000. By very slow I mean roughly 500 ms to process a row of 2,000 values. Bummer.
var ran2Darray = function(row, col){
var res = [];
for (var i = 0 ; i < row; i++) {
res[i] = [];
for (var j = 0; j < col; j++) {
res[i][j] = Math.random();
}
}
return res;
}
var myArray = ran2Darray(5, 100);
var offset = 2;
for (i = 0; i < myArray.length; i++) {
aRow = myArray[i];
st = Date.now();
aRow.map(function addNumber(offset) {myArray[i] + offset*i; })
end = Date.now();
document.write(end - st);
document.write("</br>");
myArray[i] = aRow;
}
I want to avoid any added libraries or frameworks, unless of course, that is my only option. Can this code be made faster, or is there another direction I can go, like passing the calculation to another language? I'm just not familiar with how people deal with this sort of problem. forEach performs roughly the same, by the way.
You don't have to rewrite array items several times. .map() returns a new array, so just assign it to the current index:
var myArray = ran2Darray(5, 100000);
var offset = 2;
var performOperation = function(value, idx) {
return value += offset * idx;
}
for (i = 0; i < myArray.length; i++) {
console.time(i);
myArray[i] = myArray[i].map(performOperation)
console.timeEnd(i);
}
It takes like ~20ms to process.
Fiddle demo (open console)
Ok, Just a little modification and a bug fix in what you have presented here.
function addNumber(offset) {myArray[i] + offset*i; }) is not good.
myArray[i] is the first dimention of a 2D array why to add something to it?
function ran2Darray (row, col) {
var res = [];
for (var i = 0 ; i < row; i++) {
res[i] = [];
for (var j = 0; j < col; j++) {
res[i][j] = Math.random();
}
}
return res;
}
var oneMillion = 1000000;
var myArray = ran2Darray(10, oneMillion);
var offset = 2;
var startTime, endTime;
for (i = 0; i < myArray.length; i++) {
startTime = Date.now();
myArray[i] = myArray[i].map(function (offset) {
return (offset + i) * offset;
});
endTime = Date.now();
document.write(endTime - startTime);
document.write("</br>");
}
try it. It's really fast
https://jsfiddle.net/itaymer/8ttvzyx7/
I've got this array in a "global" position (out of every function in my doc).
var arrayBidimensional;
Then, i'm trying to filling it like this:
var objetoLetra = new objectLetter("","","","","");
arrayBidimensional=new Array(tamano);
for (i=0; i <tamano; i++)
arrayBidimensional[i]=new Array(tamano);
var random = Math.floor((Math.random()*26)+0);
for (var i = tamano - 1; i >= 0; i--)
{
for (var j = tamano - 1; j >= 0; j--)
{
random = Math.floor((Math.random()*26)+0);
objetoLetra.letra = letras[random];
objetoLetra.letraposx = j;
objetoLetra.letraposy = i;
objetoLetra.formapalabra = "no";
objetoLetra.iden = j+""+i;
arrayBidimensional[i][j] = objetoLetra;
}
}
so when i tried to reach to this array in some position like array[X][X]
all i've got is the very first position. Example: if the first position (That is 0,0) is "A", then, the entire array got "A" on every single position, even if it is [(max position), (max position)].
How do i see that?, well, i'm building a Table with td-s like this:
'<td width="30">'+arrayBidimensional[i][j].letra+'</td>'
Then, the entire table is just a lot of "A" every single cell... So... What i am doing wrong?
Please and thank you!
You need to create a new objectLetter for each location in the array:
arrayBidimensional = new Array(tamano);
for (i=0; i < tamano; i++) {
arrayBidimensional[i] = new Array(tamano);
}
for (var i = tamano - 1; i >= 0; i--)
{
for (var j = tamano - 1; j >= 0; j--)
{
var objetoLetra = new objectLetter("","","","","");
var random = Math.floor((Math.random()*26)+0);
objetoLetra.letra = letras[random];
objetoLetra.letraposx = j;
objetoLetra.letraposy = i;
objetoLetra.formapalabra = "no";
objetoLetra.iden = j+""+i;
arrayBidimensional[i][j] = objetoLetra;
}
}
Here's what a Multidimensional Array should look like in JavaScript:
var multi = [['String', 0, 'something else'],['another String', 42, 'whatever']];
or
var multi = new Array(new Array('String', 0, 'something else'), new Array('another String', 42, 'whatever'));
console.log(multi[1][2]); // 'whatever'
console.log(multi[0][1]); // 0