I'm trying to figure out how to use a Global Array and holding 500 in an array and holding a picture/jpg to be 20x20 in size. Basically the picture would be multiplied on the screen.
For example this is what I have right now.
(function(food) {
food.arr[500];
} ) (this);
if I need to call on a picture to multiple it randomly all the time. How would this be done?
I'm still thinking about just Java, NOT JavaScript.
I dont think that you are need Global array.
Try something like this.
// Step 1 make array
var arrayFoo = ["someImageLink","anotherImageLink"/*,....etc etc*/];
var output = "";
// Step 2 print images to screen
for(var i = 0; i < arrayFoo.length; i++){
output += "<img src='"+arrayFoo[i]+"'></img>"
}
// Output the code to screen what everway you want
Related
I am a "new" developer into the foray of Web Development and I have come across an issue I was hoping that you fine people on Stack Overflow would be able to help me with. I have asked several Cadre and Instructors in my class and we are all stumped by it.
To start with I have decided to put all of my code on a Gitlab repo so if you want to look at the whole thing (or if you want to add to it let me know): Link to Github Repo. I fiqured you guys don't want the whole thing posted as a wall of text and rather some snip-its of what in the file I specifically. But it is relitively small file
I am useing simple JavaScript as well as Node.Js to be able to build a working calculator in the back end that I can use as a template for any other project I will need to work on in the future. For now I am trying to just get it working by imputing things via the console.
I have made a way for what is imputed in Node and to an imputArray var I have set up and the Array goes something like this:
[(command), (num1), (num2), (num3), ...]
I set up a switch function that runs a block of code based on what command was given (add, subtract, divide, etc..). As well as separating the command from the number and putting them inside another array.
The part I need some help with is with getting the block of code to work for what I want it to do. I have got it set up to run rather easily on two numbers but I want it to handle as many numbers as I want to throw at it. I tried various forms of for loops as well as forEach loops and I cant seem to get it working.
case 'divide':
for (i = 1; i < numArray.length; i++) { // If any number besides the first is 0 spit out this
if (numArray[i] === 0) {
consol.log("You canot divide by zero!");
}
else {
var previousTotal = numArray[0]; //Inital number in array
for (i = 1; i < numArray.length; i++) {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal // Pushes end total to result
}
break;
I have gone through several different versions of the above code (such as using for loops instead) but this is pretty much what I ended up with. I'm sure there is an easier way and more sane way to do what I am trying to do, but if I knew how I wouldn't be here.
Essentially this is the ideal thing I want to do but I cant find a way to do it: I want to run a small block of code the index of the number array, minus one. In this case it is dividing the previous number by the next number in the array.
So it only runs if there are more then one in the array and it does the function to the previous number, or total from the last one in the array.
This is pretty much the only thing holding me back from finishing this so if someone can take the time to look at my crapy code and help it do what I want it to do that would be awesome.
Your code is reseting result each time the outer loop iterates so it will just equal what ever the last prev Total is. Basically every loop but the last is irrelevant. Do you want to add them to result? If so you want:
result += previousTotal
Or if you want an array of the answers you want:
result.push(reviousTotal)
Sorry not 100% what you want. Hope this helps!
You just need one loop, and you probably want to stop iterating if a 0 occurs:
result = numArray[0]; //no need for another variable
for (var i = 1; i < numArray.length; i++) { // declare variables!
if (numArray[i] === 0) {
console.log("You canot divide by zero!"); // typo...
break; // exit early
}
result = result / numArray[i];
}
For sure that can be also written a bit more elegantly:
const result = numArray.reduce((a, b) => a / b);
if(isNaN(result)) {
console.log("Can't divide by zero!");
} else {
console.log(`Result is ${result}`);
}
I assume you want the divide command to do ((num1/num2)/num3)/...
There are couple of issues in the code you posted, I will post a version that does the above. You can inspect and compare it your version to find your mistakes.
// divide, 10, 2, 5
case 'divide':
if (numArray.length < 2) {
console.log("no numbers in array")
break;
}
// previousTotal starts with 10
var previousTotal = numArray[1];
// start from the second number which is 2
for (i = 2; i < numArray.length; i++) {
if (numArray[i] === 0) {
console.log("You canot divide by zero!");
}
else {
previousTotal = previousTotal / numArray[i]; // for each number in array divide to the previous number
}
}
result = previousTotal;
// result will be (10/2)/5 = 1
break;
Just playing around a bit, but noticed it's taking way too long for page to load, is there anyway to get it to print out one line at a time instead of having to wait till the entire page is loaded.
limits(){
var a = 0;
for (var i = 0; i < 1000; i++) {
for (var ii = 0; ii < 1000; ii++) {
document.getElementById('foo').innerHTML += "<p>" + a + "</p>";
a * 2;
}
}
}
Now how would I be able to control this better to where regardless of how long it takes to load print as soon as ready and even slowing it down would be fine.
The javascript method window.requestAnimationFrame(callback) will call your callback function on the next animation frame. It's commonly used for animation, and will probably work well for what you're doing.
To modify your code to use requestAnimationFrame, you have to make your function print a small chunk on its own, with a reference to know what chunk to print. If you stored your page contents in an array, for example, that could just be a starting index and a length. Since you are printing the increasing powers of 2, you can just pass in the last power of two and the number of lines you want to print for each run of the function.
You'll also need an exit condition -- a check within limits that if true, returns without requesting the next frame. I simply put a hard cap on the value of a, but you could also check that the index is less than array length (for my array of page contents idea above).
Because requestAnimationFrame passes in a function name as a callback, you can't pass arguments into it. Therefore, you have to use bind to sort of attach the values to the function. Then, within the function, you can access them using this. config is just an object to hold the initial arguments you want the function to have, and then you bind it, which allows you to access them within the function with this.numLines and this.a.
Then, when you request the next frame, you have to bind the values to limits again. If you are alright with keeping the arguments the same, you can just do limits.bind(this). But if you want to change them, you can create another object in a similar way to how I wrote config and bind that instead.
The following code seems to be a basic example of roughly what you're looking for:
var foo = document.getElementById('foo');
var maxA = 1000000000000000000000000000000000;
function limits() {
for(var i=0; i<this.numLines; ++i) {
foo.innerHTML += "<p>" + this.a + "</p>";
this.a *= 2;
if(this.a > maxA) {
return;
}
}
requestAnimationFrame(limits.bind(this));
}
config = {
numLines: 3,
a: 1
};
requestAnimationFrame(limits.bind(config));
And is implemented in JSFiddle here. I've also implemented a version where it puts each line at the top of the page (as opposed to appending it to the bottom), so that you can see it happening better (you can find that one here).
You can do something like this:
limits(){
var a = 0;
for (int i = 0; i < 1000; i++) {
for (int ii = 0; ii < 1000; ii++) {
setTimeout(function(){
document.getElementById('foo').innerHTML += "<p>" + a + "</p>";
a * 2;
}, 0);
}
}
}
You can adjust the time in the setTimeout, but even leaving it as zero will allow a more interactive experience even while the page builds. Setting it to 10 or 100 will of course slow it down considerably if you like.
I want to represent a board game in javascript and for that i need a bidimensional array.
I have different board sizes, so i need to initialize the array with the board size in the beginning. I am a java programmer so i know that in java when you want a bidimensional array you just do:
int board_size = 6;
String board = new String[board_size][board_size];
How can i achieve this with javascript? I have searched and found some ways of doing this, but all much less intuitive than this one.
It is not required like in Java or C#. The Javascript arrays grow dynamically, and they are optimized to work that way, so you don't have to set the size of your matrix dimensions upfront.
However, if you insist, you could do something like the following to pre-set the dimensions:
var board = [];
var board_size = 6;
for (var i = 0; i < board_size; i++) {
board[i] = new Array(board_size);
}
So to summarize you just have three options:
Initialization with a literal (like in #Geohut answer)
Initialization with a loop (like in my example)
Do not initialize upfront, but on-demand, closer to the code that access the dimensions.
With JavaScript it is not a static language like Java. It is dynamic. That means you can create the array without a need to preset the size of the array, but if you want you can procreate an array of the size you want.
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
If you need to add to it just do
items.push([7,8]);
That will add the next element.
Code taken from old stack overflow post: How can I create a two dimensional array in JavaScript?
Edited to properly make I in items same as variable declaration.
I'm trying to write a function in javascript that can devide x elements over y elements in every possible combination. I included a picture of what I want to achieve.
It's some basic brute force I guess, but I can't figure out how I should write the loops. I hope somebody can help me.
Thanks in advance
for the code. I don't have much yet, because what I tried didn't work.
But I have a globaly defined empty array which is X long. And I have another array full of THE SAME elements and want every combination of the array of length X containing the elements of array with length Y.
You are looking for combination. In your case n=x and k=y.By borrowing code from here, you can visualize it by this way:
var x = 7;
var y = 3;
comb(y,x).forEach(function(item){
var tr = $('<tr>');
for(var i=0; i<x;++i){
tr.append('<td>');
}
var chunks = item.split(" ");
chunks.pop();
chunks.forEach(function(index){
tr.find("td").eq(+index).addClass("black");
});
$("table").append(tr);
});
DEMO
I am trying to create an Animated Responsive Image Grid using this.
In it's source code you can see that the code for those images are physically typed out individually rather than using a function that repeats it for a an 'n' amount of times. If you have a lot of pictures to list, that's painfully repetitive.
Therefore, I created this function:
function showImg() {
for (var imgNum = 1; imgNum < 100; imgNum++) {
document.write("<li><a href='#'><img src='img/" +imgNum+ ".jpg'/></a></li>");
}
}
showImg();
This function is fine, however, every time the page is refreshed, it starts out with the same images in the same order. I don't want that. I want them to start with random images every time the page is refreshed. So I created a new code for that:
function showImg() {
var imgNum = Math.floor((n+1)*Math.random());
document.write("<li><a href='#'><img src='img/" +imgNum+ ".jpg'/></a></li>");
}
var n = 100;
for (var i=0; i<n; i++) {
showImg();
}
Great! Now, a new problem is that sometimes there will be duplicates. I don't want duplicates, not when the first set of images are loaded and not when the images begin to rotate/cycle through the animation. How do I achieve this? Thanks.
Create an array of the numbers 1-100. Then "scramble" them: for 500 times, pick 2 of the array elements and swap their values. Finally, loop through that scrambled array, and show the image associated with the value of that array element.