java script array assignation mistake - javascript

var UserBoard = new Array(20,20);
for(var i = 0; i < 21; ++i){
for(var j = 0; j < 21; ++j){
UserBoard[i,j] = 0;
}
}
document.write(UserBoard[3,5]);
UserBoard[4,5]=1;
document.write(UserBoard[3,5]);
http://jsfiddle.net/XbyqN/2/
it's quite simple but I don't know why does this. Alert should be 0, not 1 since I've initialized the 2d array to 0.
Can someone explain me why?

Let's break it down
var UserBoard = new Array(20,20);
You are creating an array with two slots, both of them containing the value "20" (int). So your array is [20, 20]
Next, your loop :
for(var i = 0; i < 21; ++i){
for(var j = 0; j < 21; ++j){
UserBoard[i,j] = 0;
}
}
Two dimensional arrays are not defined like this. In that case, only the "j" counter does something. The "i" is simply ignored. So you end up with an array as follow : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Next, the assignement :
UserBoard[4,5]=1;
Is equivalent to :
UserBoard[5]=1;
And your alert :
alert("test: " + UserBoard[3,5]);
Is equivalent to :
alert("test: " + UserBoard[5]);
That's why you get "1" as alert.
If you want two dimensional arrays, you should use the following notation :
UserBoard[4][5] = 1;
Read it all here on MDN : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

You want UserBoard[i][j] instead of UserBoard[i,j].
Multidimensional arrays don't work as you seem to think they work. They're, in fact, arrays of arrays.
Use this :
var UserBoard = new Array(20);
for(var i = 0; i < 20; ++i){
UserBoard[i] = new Array(20);
for(var j = 0; j < 20; ++j){
UserBoard[i][j] = 0;
}
}
I suggest you start using console.log and Chrome's developer tool to debug your code (or Firebug). Try this at the end of your code and then type the F12 key :
console.log(UserBoard);

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
var UserBoard = new Array(20,20); // [20, 20]
for(var i = 0; i < 21; ++i){
for(var j = 0; j < 21; ++j){
UserBoard[i,j] = 0; // UserBoard[j] = 0
}
}
UserBoard[4,5]=1; // UserBoard[5] = 1
alert("test: " + UserBoard[3,5]); // UserBoard[5]
What you want is:
var UserBoard = [];
for (var i = 0; i < 20; i++) { // i < 20
UserBoard[i] = [];
for (var j = 0; j < 20; j++) {
UserBoard[i][j] = 0;
}
}
UserBoard[4][5]=1;
alert("test: " + UserBoard[3][5]);

When creating a new array using the array constructor (new Array), the arguments have different meanings, depending on the type and total number of arguments.
var array20long = new Array(20);// = [undefined,undefined,undefined,....].length === 20
var arrayString = new Array('foo');// = ['foo']
var yourArray = new Array(20,20);// = [20,20]
Put simply: passing 1 integer to the array constructor, creates an array with length equal to the int passed, passing several integers will result in 1, 1 dimensional array with a length equal to the total number of argumens. In your case, two integers creating an array with 2 values. Each index will be initialized to its corresponding argument. In your case: index 0 === 20, index 1 === 20, if you had written new Array(20,10), the result would be an array like [20,10].
You get the basic idea.It is important to note that accessing multi dimensional arrays using a comma won't work: instead of writing arr[1,2] you should have written arr[1][2]. Google some introductory tutorials to JavaScript, it won't hurt... and you'll soon learn why using the array constructor isn't the best way of creating arrays

Related

For loop increment by values taking from another array

var z=[1,1,1,1,1,5,1,1,3]
var data1=[];;
for(var q=0;q<20;q=q+z)
I want to increment values not in a regular pattern like q++, but the increment is to be done in a pattern like +1,+1,+1,+1,+1,+5,+1,+1,+3. Is it possible?
What you want
The following adds successive items in z to q during each iteration of the loop.
var z = [1,1,1,1,1,5,1,1,3];
for (var q = 0, index = 0; q < 20; q = q + z[index++]) {
}
Side note
You will clearly have an issue before the loop finishes. Your loop runs until q is 20, but you will run out of items in your z array before q reaches 20. You only have 9 items in your z array, which means you can access up to the 8th index. Accessing indexes beyond the array length will return undefined. Adding undefined to q will produce NaN.
q:0, index: 0
q:1, index: 1
q:2, index: 2
q:3, index: 3
q:4, index: 4
q:5, index: 5
q:10, index: 6
q:11, index: 7
q:12, index: 8
q:15, index: 9 (danger)
End Early
Depending on what you actually want, one way to workaround this is to change your loop ending logic to take into account the length of the z array, compared to the index. This is unnecessary if your z array is actually much longer.
var z = [1,1,1,1,1,5,1,1,3];
for (var q = 0, index = 0; q < 20 && index < z.length; q = q + z[index++]) {
}
That should do it - no inner loops. Watch out for i < n from now on.
var z=[1,1,1,1,1,5,1,1,3];
for(var i = 0, j = 0; i < 20; i+=z[j++]) {
console.log(i, j)
}
Yes, what you want to do is possible. In a for statement, the final portion of it says "do this at the end of each iteration", then on the next iteration check to see if the condition is still true.
var z=[1,1,1,1,1,5,1,1,3]
var data1=[];;
for(var q=0;q<20;q=q+z)
You problem is here: q=q+z. z is an array, and not a number, you need to specify which value in the array you want to add to q. You could so something like this:
for(var q=0;q<20;q=q+z[q]) or this for(var q=0;q<20;q=q+z[2]) but you need something to specify which value in the array you want to use. You could create a separate value to increment so that the indexed value of array z uses the next value on each loop.
You can define multiple variables in the first expression of the for loop and then use it to index the z array like so:
var z=[1,1,1,1,1,5,1,1,3];
for(var q=0, i=0;q<20;q+=z[i], i++){
console.log(q);
}
Are you looking for something like this?:
for(var q=0;q<z.length;q=q + z[q]){
console.log("z[q] = " + z[q]);
console.log("q =" + q);
}
You could use an additional variable as index for the array.
With incrementing the index variable, you could use a remainder operator to keep the index smaller than the length of z.
var z = [1, 1, 1, 1, 1, 5, 1, 1, 3],
data = [];
for (var i = 0, q = 0; q < 30; q += z[i], i = (i + 1) % z.length) {
console.log(i, z[i], q);
data.push(q);
}
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
function irregfor(func){
var total=0;
while(total<20){total=[1,1,1,1,1,5,1,1,3].reduce((index,inc)=>{func(index+=inc);return index;},total)}
}
Use like this:
irregfor(function(index){
console.log(index);
});
http://jsbin.com/vakutonave/edit?console
This will work if you increment only one var in your code...
var count=0;
function irregIncre(val){
var arr = [1,1,1,1,1,5,1,1,3];
if(count >= arr.length){ count = count % arr.length; }
return val + arr[count++];
}
var num = 0;
num = irregIncre(num); //many times you wish...
To increment more variables, I would use an identifier
var countA=[];
function irregIncreM(val, id){
countA[id] = countA[id] ? countA[id] : 0;
var arr = [1,1,1,1,1,5,1,1,3];
if(countA[id] >= arr.length){ countA[id] = countA[id] % arr.length; }
return val + arr[countA[id]++];
}
var num1 = 0;
var num2 = 0;
num1 = irregIncre(num1, 'num1'); //many times you wish...
num2 = irregIncre(num2, 'num2'); //many other times you wish...
Link to JsBin
Something like this. Using a counter variable to increment the value of Z.
var z=[1,1,1,1,1,5,1,1,3]
var data1=[1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19, 20, 21, 22, 23, 24, 35];;
var i = 0;
var zincrement = z[i];
for(var q=0;q<20;q=q+zincrement){
console.log(data1[q]);
i++;
zincrement = z[i];
}

JavaScript pushing to index 1 instead of 0

I have a JavaScript variable, and I'm trying to initialize it in another function, with the following for loop:
var test = {
det: [{x: -1, y: -1}]
};
for (var i = 0; i < 4; i++) {
test.det.push({x:10+i, y:10});
}
console.log(test.det);
For some reason, I still get -1 & -1 as my values of x & ywhen I try to access test.det[0]. I only get the first values pushed when I access index 1. It seems like all my indices are shifted but I have no idea why that would be happening.
Array#push will add another item after the current last item. To re initialize use assignment =:
var test = {
det: [{x: -1, y: -1}]
};
for (var i = 0; i < 4; i++) {
test.det[i] = ({x:10+i, y:10});
}
console.log(test);
Or just clear the array, and use Array#push:
var test = {
det: []
};
for (var i = 0; i < 4; i++) {
test.det.push({x:10+i, y:10});
}
console.log(test);

Formula for getting a single 0-based index from two 0-based for loop iterators?

This has got to be a thing. If I have something like this in Javascript
var c = 0;
var arr = [
[a,b,c,d],
[e,f,g],
[h,i,j,k,l]
];
for(var i = 0; i < arr.length; i++){
for(var j = 0; j < arr[i].length; j++){
}
}
How do I get a single 0-based index based off of i and j?
To be clear, after every iteration of the inner j loop c should increment to the next number in 0 - 11.
I think this is what you want
var arr = [
['a','b','c','d'],
['e','f','g'],
['h','i','j','k','l']
];
var output = [];
arr.forEach(function(item){
output.concat(item);
});
Output:
['a','b','c','d','e','f','g', 'h','i','j','k','l']

javascript split without losing first element (not RegEx)

I have a string containing ones and zeros split by "," and ";".
var x = "1,1,0;1,0,0;1,1,1;"; x.split(";");
This wil output an array with just two strings: 1,0,0 and 1,1,1.
What I want is to put all of these numbers in a two dimensional array:
1 1 0
1 0 0
1 1 1
If there is a smarter way than just split the string, please let me know.
Otherwise, please tell me how to fix the problem above.
You need to put quotes around your string.
Commentors are correct, your array contains all 3 strings. did you forget that array indices start at 0, not 1?
x.split does not modify x, it returns an array
You probably want something like this
var str = "1,1,0;1,0,0;1,1,1";
var arr = str.split(";");
for (var i = 0, len = arr.length; i < len; i++)
{
arr[i] = arr[i].split(",");
}
and to verify the result
for (var i = 0, len = arr.length; i < len; i++)
{
for (var j = 0, len2 = arr[i].length; j < len2; j++)
{
document.write(arr[i][j] + " | ");
}
document.write("<br>");
}
given the string:
var x = "1,1,0;1,0,0;1,1,1";
you can get a two dimensional array of zeros and ones this way:
var st = x.split(";")
var twoDimensionalArray = st.map(function(k){
return k.split(",");
});
of course, thanks to JS method chaining, you can do the whole thing this way:
var twoDimTable = x.split(";").map(function(k){
return k.split(",");
});
the result:
[
["1","1","0"],
["1","0","0"],
["1","1","1"]
]
well, to get the result as
[
[1,1,0],
[1,0,0],
[1,1,1]
]
you can do a loop and for each value k within the array do k = +k;
and you will get numbers instead of strings. However, JavaScript will do the casting
for you when you use these values within an operation with a number.

Dynamically create index in two dimensional array

Having some trouble with this script. It iterates through a two dimensional array and adds each corresponding index together. So basically arr[0][1] + arr[0][2] + arr[0][3] ... arr[1][1] + arr[1][2] + arr[1][3] ...etc.
This first one works fine. So my logic is ok. My problem here is that I can't create the indices dynamically. I don't think a push will work since I'm summing values here.
var cat_stats_week_radar = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0]];
for (var i = 0; i < cat_stats_week.length; i++) {
for (var j = 0; j < cat_stats_week[0].length; j++) {
cat_stats_week_radar[0][j] += +(cat_stats_week[i][j]);
}
}
This one doesn't work, I don't get an error, just a bunch of NaN values.
var cat_stats_week_radar = [[]];
for (var i = 0; i < cat_stats_week.length; i++) {
for (var j = 0; j < cat_stats_week[0].length; j++) {
cat_stats_week_radar[0][j] += +(cat_stats_week[i][j]);
}
}
Here are the arrays I'm working with.
Array to add:
var cat_stats_week = [
[0,0,0,0,0,0,0,1,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,1,0,0,0,0,0,0,0,0,0,0,0]
];
Resulting array:
var cat_stats_week_radar = [[0, 0, 1, 0, 0, 0, 2, 1, 0, 0, 0, 0, 2, 0]];
You need to initialize it with the right number of zeroes:
var cat_stats_week_radar = [[]];
for (var i = 0; i < cat_stats_week[0].length; i++) {
cat_stats_week_radar[0].push(0);
}
And with Underscore.js:
_.map(_.zip.apply(null, cat_stats_week), function(a) {
return _.reduce(a, function(a, b) {
return a + b
})
});

Categories

Resources