increasing the row number using JavaScript? - javascript

I'm trying to increase the row each time around the loop, but it's not increasing is there something wrong with my JavaScript code?
var image= [];
for (var i = 0; i < test.length; i++) {
var avatar = test[i].image; // The profile image
var row =5;
if(i % 2 === 0){
image[i]= Titanium.UI.createImageView({
top:row,
image:avatar
});
win.add(image[i]);
//trying to increase the image
row =row+200;
} else if(i % 2 === 1) {
image[i]= Titanium.UI.createImageView({
top:row,
image:avatar
});
win.add(image[i]);
}
}

Can't say I'm certain of what you're attempting to achieve, but at the beginning of your for iteration you're resting row to 5. You should move your var row=5; declaration to the top with var image[];
You might also consider the short form row+=200;

try to move this line upper outside of the loop :
var image= [];
var row =5;
for (var i = 0; i < test.length; i++) {
...
}

You are initializing row in each start of loop. Try taking your var row = 5 outside of the loop:
var image= [];
var row =5;
for (var i = 0; i < test.length; i++) {
var avatar = test[i].image; // The profile image
...
}

Related

Put a line break in a for loop that is generating html content

I have a for loop that is generating some HTML content:
var boxes = "";
for (i = 0; i < 11; i ++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
}
document.getElementById("id").innerHTML = boxes;
I want to display 3 boxes in one row, then below them 2 boxes in one row, then 1, then 3 again, 2, and 1.
First i thought of using the if statement to check whether i > 2 to add a line break, but it will also add a line break after every box past the third one. Nothing comes to mind, and my basic knowledge of javascript tells me I'll have to make a loop for each row I want to make. Any advice?
I would use a different approch :
Use a array to store the number of item per row :
var array = [3, 2, 1, 3, 2];
Then, using two loops to iterate this
for(var i = 0; i < array.length; i++){
//Start the row
for(var j = 0; j < array[i]; ++j){
//create the item inline
}
//End the row
}
And you have a pretty system that will be dynamic if you load/update the array.
PS : not write javascript in a while, might be some syntax error
Edit :
To generate an id, this would be simple.
create a variable that will be used as a counter.
var counter = 0;
On each creating of an item, set the id like
var id = 'boxes_inline_' + counter++;
And add this value to the item you are generating.
Note : This is a small part of the algorithm I used to build a form generator. Of course the array contained much more values (properties). But this gave a really nice solution to build form depending on JSON
You can try something like this:
Idea
Keep an array of batch size
Loop over array and check if iterator is at par with position
If yes, update position and index to fetch next position
var boxes = "";
var intervals = [3, 2, 1];
var position = intervals[0];
var index = 0;
for (i = 0; i < 11; i++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
if ((position-1) === i) {
boxes += "<br/>";
index = (index + 1) % intervals.length;
position += intervals[index]
}
}
document.getElementById("content").innerHTML = boxes;
.box{
display: inline-block;
}
<div id="content"></div>
var boxes = "",
boxesInRow = 3,
count = 0;
for (i = 0; i < 11; i ++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
count++;
if(count === boxesInRow) {
boxes += "<br/>";
boxesInRow -= 1;
count = 0;
if (boxesInRow === 0) {
boxesInRow = 3;
}
}
}
document.getElementById("id").innerHTML = boxes;
var i;
var boxes = "";
for (i = 0; i < boxes.length; i++) {
boxes += "<div class=""><img src=""/></div>";
function displayboxes() {
"use strict";
for (i = 0; i < boxes.length; i++) {
out.appendChild(document.createTextNode(boxes[i] + "<br>"));
}
}
displayboxes(boxes);

Simulation of mouses moving, don't work

I'm trying to create a simulation of 150 mouses moving inside a 20x20 grid in p5.js (A processing like libary). First I'm spawning 150 mouses random places and everything goes fine. But after I have spawned the mouses I am trying to make them move to one of their neighbors. Instead of moving to one of the neighbors and make the current square empty it stays on the one that it already was one + it moves to the next one so instead of having 150 mouses i suddenly have 300... I have tried changing the code for hours but I can't find the proplem... Here is my code:
var w = 40;
var grid = [];
var mouses = 10;
var mouseAmount = [];
var Mouse;
var current;
function setup() {
createCanvas(800, 800);
cols = floor(width/w)
rows = floor(height/w)
// frameRate(60);
for (var j = 0; j < rows; j++) {
for ( var i = 0; i < cols; i++) {
var cell = new Cells(i,j);
grid.push(cell);
}
}
amount = new Amount;
}
function draw() {
background(51);
for ( var i = 0; i < grid.length; i++) {
grid[i].show();
}
amount.run();
}
function index(i, j) {
if (i < 0 || j < 0 || i > cols-1 || j > rows-1 ) {
return -1;
}
return i + j * cols;
}
function Cells(i, j) {
this.i = i;
this.j = j;
this.active = false;
this.moveCell = function() {
var neighbors = [];
var top = grid[index(i, j -1)];
var right = grid[index(i+1, j)];
var bottom = grid[index(i, j+1)];
var left = grid[index(i-1, j)];
if (top) {
neighbors.push(top)
}
if (right) {
neighbors.push(right)
}
if (bottom) {
neighbors.push(bottom)
}
if (left) {
neighbors.push(left)
}
if(neighbors.length > 0) {
var r = floor(random(0, neighbors.length));
return neighbors[r];
} else {
return undefined;
}
}
this.show = function() {
var x = this.i*w;
var y = this.j*w;
stroke(255);
noFill();
rect(x,y,w,w);
if(this.active == true) {
fill(155, 0, 255, 100)
rect(x, y, w, w)
}
}
}
function Amount() {
this.run = function() {
var r = floor(random(grid.length))
for (var i = 0; i < mouses; i++) {
var mouse = grid[r];
mouseAmount.push(mouse)
}
if (mouseAmount.length < 1499) {
for (var i = 0; i < mouseAmount.length; i++) {
mouseAmount[i].active = true;
}
}
if (mouseAmount.length > 1499) {
Next();
}
}
}
function Next(i,j) {
for (var i = 0; i < mouseAmount.length; i++) {
current = mouseAmount[i];
var nextCell = current.moveCell();
if (nextCell) {
nextCell.active = true;
current.active = false;
current = nextCell;
}
}
}
Thank you in advance :)
I don't really understand exactly what your code is supposed to do, but a few things stand out to me about your code:
Problem One: I don't understand how you're iterating through your grid array. You seem to be iterating over mouseAmount, which seems to hold random cells from the grid for some reason? That doesn't make a lot of sense to me. Why don't you just iterate over the grid array directly?
Problem Two: You then move the cells randomly to a neighbor, but you don't take into account whether the neighbor is already active or not. I'm not sure what you want to happen, but this seems a bit strange.
Problem Three: Usually with simulations like this, you have to copy the next generation into a new data structure instead of modifying the data structure as you step through it.
The biggest problem is that you haven't really explained what you want your code to do, or what this code does instead, or how those two things are different. But if I were you, I'd make the following changes:
Step One: Iterate over your grid array in a more reasonable way. Just iterate over every index and take the appropriate action for every cell. If I were you I would just use a 2D array and use a nested for loop to iterate over it.
Step Two: Make sure your logic for moving to a neighbor is correct. Do you want cells to move to already active cells?
Step Three: Make a copy of the grid before you modify it. Think about it this way: as you iterate over the grid, let's say you move a cell down one row. Then you continue iterating, you'll reach the newly active cell again. In other words, you'll touch the same active cell twice in one generation, which is definitely going to mess you up.
A word of advice: get this working for a single active cell first. It's really hard to tell what's going on since you have so many things going on at one time. Take a step back and make sure it works for one active cell before moving up to having a whole grid.

reseting filter on datatable to include full search

working on from my previous Q
http://stackoverflow.com/questions/33550384/check-value-in-table-row-column
val = 2
get table.row[where val = data-uid]
check next row
if table.rows[data-uid = val] continue until it is not the same, when value is different pass back
var newVal = ?
this all works but only for the first button click. on the second button click the table holds the value from the previous search as opposed to checking all the values in the jquery datatable. I tried reseting the filters but this didnt work...
t.fnResetAllFilters(false);
//t.fnResetAllFilters();
// t.fnFilter('');
so basically the first time round time round
var elements = document.getElementsByTagName('tr');
var elementsLength = elements.length;
elements.length returns a value ofd 10. but because currentElement returns 4 results the next time round elements.length only contains 4 results
loop1:
for (var i = 0; i < elements.length; i++)
{
var currentElement = elements[i].getAttribute('data-uid');
loop2:
for (var j = i + 1; j < elements.length; j++)
{
var nextElement = elements[j].getAttribute('data-uid');
if (currentElement !== nextElement)
{
rowId = elements[j].getAttribute('data-uid');
break loop1;
//return;
}
}
}

Can someone explain me this function for creating grid with JS/jQuery?

I am learning jquery/js and I want to create grid made of divs. This is script doing just that, but I cant fully understand it..
function displayGrid (n) {
var size = 960;
var boxSize = (960 - 4*n)/n;
var wrap = $(".wrap").html("");
for (var j = 0; j < n; j++) {
for (var i = 0; i < n; i++) {
wrap.append( $("<div></div>").addClass("square").height(boxSize).width(boxSize) );
}
wrap.append($("<div></div>").css("clear", "both"));
}
}
In html I have empty wrap class.
Also, there is this function which I understand :)
function setGrid() {
var col = prompt("Enter number of columns: ");
displayGrid(col);
clean();
}
Thanks
Here is a basic line by line explanation..
function displayGrid (n) {
var size = 960; //MAX SIZE TO BE COVERED BY ALL DIVS ,EVEN IF THERE ARE N NO OF DIV'S
var boxSize = (960 - 4*n)/n; //FORMULA TO DECIDE WIDTH OF EACH DIV,CAN BE DIFFERENT TOO.
var wrap = $(".wrap").html(""); //THIS IS A DIV PROBABLY WHERE YOU ARE ADDING THE NEW SMALLER DIVS
for (var j = 0; j < n; j++) {
for (var i = 0; i < n; i++) {
//TWO FOR LOOPS ,1 IS FOR LOOP THROUGH ROWS , OTHER FOR COLUMNS.
wrap.append( $("<div></div>").addClass("square").height(boxSize).width(boxSize) );
//THIS APPENDS A BLANK DIV TO DIV WITH CLASS .WRAP, AND ADDS A CLASS SQAURE, AND ALSO WITH WIDTH AND HEIGHT PROPERTY SETS EACH DIVS PROPERTY OF WIDTH AND HEIGHT.
}
wrap.append($("<div></div>").css("clear", "both"));
//THIS SHOULD BE TO MOVE TO NEXT COLUMN.
} }
Here is commented code:
//n-> seems to be the number of times to divide the grid
//1-> will get 1 square
//2-> will get 4 square
//3-> will get 9 square and so on... n^2
function displayGrid (n) {
var size = 960;
//This seems to calculate size of the squares to fit inside the give area
// of 960: 960/4
//-4*n I guess is the border size to remove from each square in order to have an exact match
var boxSize = (960 - 4*n)/n;
//this get the grit container, empties it
var wrap = $(".wrap").html("");
//now print each square on the document
for (var j = 0; j < n; j++) { //columns
for (var i = 0; i < n; i++) { //rows
wrap.append( $("<div></div>").addClass("square").height(boxSize).width(boxSize) );
}
//this is done to go in the next row, since we are using divs...
wrap.append($("<div></div>").css("clear", "both"));
}
}

Filling up a 2D array with random numbers in javascript

I'm really sorry if anything like this has been posted here before but I couldn't find anything, I'm kinda new to the site still!
So for a while now I've been learning a bit about game development through html5 and javascript and I stumbled upon making tileset maps, I now have a tileset and an 2D array that I want to put certain tiles in (the number varies between 6 and 10 in this case).
I figured it could be a cool function to make the map choose between a small set of similar tiles so I don't have to specifically number every tile in the array(just define the type)
The method I have currently is probably the best for being able to define types but I want something that looks a bit cleaner and/or information to why my "cleaner" version dosen't work.
var ground = [
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()],
[tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile(),tile()]];
function tile() {
var y = (Math.random() * 5 | 0) + 6;
return y;
}
This is the code I've been using so far, I have to edit every element of the code with the tile() function to get a random number in each one, what I wanted to have was something like this:
for (var i = 0 ; i < 15; i++) {
for (var j = 0; j < 9; j++) {
ground[[i],[j]] = (Math.random() * 5 | 0) + 6;
}
}
to fill the array without having to add the function to each spot.
I have a feeling that I'm missing a return function or something along those lines but honestly I have no idea.
You were thinking in the right direction but there are some errors in your code ;)
You have to initialize the array first before you can push elements into it.
And you were counting i++ twice
Javascript
var ground = []; // Initialize array
for (var i = 0 ; i < 15; i++) {
ground[i] = []; // Initialize inner array
for (var j = 0; j < 9; j++) { // i++ needs to be j++
ground[i][j] = (Math.random() * 5 | 0) + 6;
}
}
Maybe even better (reusable)
function createGround(width, height){
var result = [];
for (var i = 0 ; i < width; i++) {
result[i] = [];
for (var j = 0; j < height; j++) {
result[i][j] = (Math.random() * 5 | 0) + 6;
}
}
return result;
}
// Create a new ground with width = 15 & height = 9
var ground = createGround(15, 9);
Here's a quick example. I've created a function that will take in a width and height parameter and generate the size requested. Also I placed your tile function inside generate ground to keep it private, preventing other script from invoking it.
var ground = generateGround(10, 10); //Simple usage
function generateGround(height, width)
{
var ground = [];
for (var y = 0 ; y < height; y++)
{
ground[y] = [];
for (var x = 0; x < width; x++)
{
ground[y][x] = tile();
}
}
return ground;
function tile()
{
return (Math.random() * 5 | 0) + 6;
}
}
http://jsbin.com/sukoyute/1/edit
Try removing the comma from...
ground[[i],[j]] = (Math.random() * 5 | 0) + 6;
...in your 'clean' version. Also, your incrementing 'i' in both for loops:
for (var i = 0 ; i < 15; i++) {
for (var j = 0; j < 9; i++) {
Hopefully these changes make it work for you :)

Categories

Resources