I wish to create an array called allEnemies, which contains "bugs" which belong to a Class "Enemy". I'm trying to do it in a for loop because later on the var "bug" will be modified. The problem is that the objects created "if I'm creating them" don't get into the array "allEnmies". Thank you in advance.
var allEnemies = [];
var random_speed = function() {
return Math.floor(Math.random() * (300 - 80)) + 80;
};
var random_y = function() {
var postions = [60, 143, 226];
return positions[Math.floor(Math.random() * 3)];
};
var create_enemies = function() {
var bugs = 4;
for (var i = 0; i < bugs; i++) {
var bug = new Enemy();
bug.speed = random_speed();
bug.y = random_y();
bug.x = 0;
allEnemies.push(bug);
}
};
Demo - http://jsfiddle.net/ubkusb6r/
Ok, so a few things:
1) Since you've declared the for loop using an anonymous function assigned to a variable you need to invoke the function via that variable create_enemies(). Without this, your code won't run.
2) You need to create an Ememy constructor (if you haven't done so yet).
3) You misspell positions at one place in your code...leading to an error.
Take a look at the JSFiddle and let me know if it answers your question (the fiddle includes console.log statements to track the array).
Related
So this is what I am dealing with:
At the top of the js file i declare these variables:
let teensArray = [];
let copyteensArray = [];
let teensArrayLength = 0;
let teensArrayPlayed = 0;
$.getJSON("json/teens.json", function(data) {
teensArray = data.statements;
copyteensArray = data.statements;
teensArrayLength = data.statements.length;
$(".teens .total-cards").text(teensArrayLength + " CARDS")
});
Everytime the mode is "teens" this executes:
if (mode == "teens") {
let currStatement = copyteensArray[getRandomInt(copyteensArray.length)]
let index = copyteensArray.indexOf(currStatement)
copyteensArray.splice(index, 1);
currentPack = "TEENS PACK";
currentColor = "#23B574";
srcImg = "svg/007-party hat.svg"
playedCardsText = ++teensArrayPlayed + " / " + teensArrayLength;
console.log(copyteensArray.length);
console.log(teensArray.length);
return currStatement;
}
The problem: The teensArray has the same values as copyteensArray after the if statement.
Example values:
Before if statement
teensArray["1","2","3","4"]
copyteensArray["1","2","3","4"]
Inside if statement
copyteensArray.splice(index, 1);
After the return inside the if statement
teensArray["1","3","4"]
copyteensArray["1","3","4"]
This function executes ONLY if the user decides to go back to another screen:
function reset() {
copyteensArray = teensArray;
teensArrayPlayed = 0;
}
Am I missing something?
copyteensArray = teensArray; makes the same pointer point to both of them. Consider using copyteensArray = [...teensArray]; which assigns brand new instance of teensArray content to copyteensArray
You have a "shallow" copy of the array, ie both the array point to the same objects. Any changes made to the shallow copy will change the original object.
You can visualize it as a shortcut in Windows. Whatever change you make to the shortcut also changes the original object.
Solve this making a hard copy. There are multiple ways in ES6 to do that.
hardCopy = [...OriginalArray];
And another way is to JSON.stringify() the object and parse it back.
hardCopy = JSON.parse(JSON.stringify(OriginalArray));
For your code, fix this by changing these lines
$.getJSON("json/teens.json", function(data) {
teensArray = [...data.statements];
copyteensArray = [...data.statements];
I have an object with randomly generated data:
var obj = {
price: getRandomNumberRange(10, 200),
rooms: getRandomNumberRange(1, 5)
};
where
var getRandomNumberRange = function (min, max) {
return Math.floor(Math.random() * (max - min) + min);
};
I keep trying and failing to write a function, which will allow to create an array of 4 objects, so each objects' data will be regenerated at the time of creation. My function:
var createArr = function () {
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push(obj);
}
return arr;
};
In other words I expect to get this kind of array:
var arr = [{price:40, rooms:2}, {price:23, rooms:4}, {price:99, rooms:2}, {price:191, rooms:3}];
But I keep getting this:
var arr = [{price:40, rooms:2}, {price:40, rooms:2}, {price:40, rooms:2}, {price:40, rooms:2}];
Will appreciate your help!
UPD. Thanks to everyone who suggested more complex way to solve my problem. As soon as I progress in JS I will recheck this thread again!
It looks like you reuse the object for pushing over and over and because of the same object, it pushes the same object reference with the latest values.
To overcome this, you need to create a new object for each loop and assign the random values with short hand properties.
// inside the loop
let price = getRandomNumberRange(10, 200),
rooms = getRandomNumberRange(1, 5);
array.push({ price, rooms }); // short hand properties
I know that this is fundamental JS, but I'd like a simple explanation. From what I've read, If i declare an empty variable outside of my loop, the variable inside the loop should be accessible globally? Or am I totally wrong?
I would like to access randAd from outside my for loop.
var mobileAds = [
"mobile/bb.jpg",
"mobile/eyeko.jpg",
"mobile/farfetch.jpg",
"mobile/fsb.jpg"
];
var randNum = (Math.floor(Math.random() * mobileAds.length));
var randAd;
var i;
for (i = 0; i < mobileAds.length; ++i) {
randAd = (mobileAds[randNum]);
}
If you want to access every element of randAd outside the for loop try like this var randAd = []; to initialize it as an array. You can easily access it after your for loop but If you use it as a simple variable var randAd;then you'll get the last variable always (it overwrites). So initialize it as an array and push every element inside loop before outputting it.
var mobileAds = [
"mobile/bb.jpg",
"mobile/eyeko.jpg",
"mobile/farfetch.jpg",
"mobile/fsb.jpg"
];
var randNum = (Math.floor(Math.random() * mobileAds.length));
var randAd = []; // see the change here
var i;
for (i = 0; i < mobileAds.length; ++i) {
randAd.push(mobileAds[randNum]); // push every element here
}
console.log(randAd);
You are overthinking. You have done the hard bit in getting a random number between 0 and array's length. So, just get the ad at that index:
var randAd = mobileAds[randNum];
No need to use for loop at all.
If you would like to use randAd it should be initialised as an empty array [] and then push in that array from inside your loop randAd.push(). Like this:
var randAd=[];
var i;
for (i = 0; i < mobileAds.length; ++i) {
randAd.push(mobileAds[randNum]);
}
I have a very simple JS Arrays question, my simple canvas game has been behaving differently when I replaced one block of code with another. Could you look them over and see why they are functionally different from one another, and maybe provide a suggestion? I may need these arrays to have 20+ items so I'm looking for a more condensed style.
There's this one, which is short enough for me to work with, but doesn't run well:
var srd=new Array(1,1,1);
var sw=new Array(0,0,0);
var sang=new Array(0,0,0);
var sHealth=new Array(20,20,20);
And then there's the original one, which is longer but works fine:
var srd = new Array();
srd[1] = 1;
srd[2] = 1;
srd[3] = 1;
var sw = new Array();
sw[1] =0;
sw[2] =0;
sw[3] =0;
var sang = new Array();
sang[1] = 0;
sang[2] = 0;
sang[3] = 0;
var sHealth = new Array();
sHealth[1] = 20;
sHealth[2] = 20;
sHealth[3] = 20;
Arrays are zero-indexed in JavaScript. The first element is 0, not 1:
var srd = new Array();
srd[0] = 1;
srd[1] = 1;
srd[2] = 1;
Also, you may want to use the more common array constructor:
var srd = [1, 1, 1];
I have a feeling that you may be assuming that the first element is 1 instead of 0, which is why the first version doesn't work while the second one does.
You should do this....in Arrays values are stored as such that first one is at 0 and so on.
so 1st value will be accessed as this...
var x = abc[0]; //first value of array abc being assigned to x.
Do this (you see i actually read your question and this is what you like)
var srd=['',1,1,1];
var sw=['',0,0,0];
var sang=['',0,0,0];
var sHealth=['',20,20,20];
you can declare an array(object) in javascript like this
var x = []; -------------Literal - its a shortcut provided by JS to quickly declare something as an Array.
var x = new Array; --Array constructor
Things to look up regarding
literal
object literal
proto
word new
function object
function property prototype
You can also do these:
var x=1,y=2,
z=3,
f;
var b = something || {}; \\become a copy of object called something if it's not there then become an empty object.
It looks like one starts the arrays at index 0 and the other one starts at index 1
It depends on your implementation, but it's likely because of arrays being 0-indexed. In your first block of code, each number is offset by one index spot from the second block. The first one is equivalent to:
var srd = new Array();
srd[0] = 1;
srd[1] = 1;
srd[2] = 1;
in the way you wrote it for the second block.
I have the need to create a function from a name stored in a variable. Usually this is pretty simple, I've done it before using:
var funcName = "theName";
window[funcName] = function(){
// code here
};
However in my new usecase the function I create needs to sit inside an object called the.Name. So what I tried to do, and it doesn't work is:
var funcName = "the.Name";
window[funcName] = function(){
// code here
};
The reason it doesn't work is because I can't reference window["the.Name"] as that's invalid, the correct way is window["the"]["Name"].
Does anyone have a a solution for this problem? Basically naming a function which will sit inside an object when the name is stored in a variable.
OK, I seem to understand your problem.
Here's some code to get you started.
/**
* #param fn The function to bind.
* #param path The object to bind to.
* #param root The root object.
*/
function bindFunc(fn, path, root){
path = path.split('.');
var base = root;
for(var i=0; i<path.length-1; i++){
base = base[path[i]];
}
base[path[path.length - 1]] = fn;
}
bindFunc(function(){ }, 'the.Name', window);
I'm going to make a guess that you're trying to do something "namespace-like". Here's an article that should get you started (has some good example code, too)..
http://blogger.ziesemer.com/2008/05/javascript-namespace-function.html
If you're sure that all object till the last one exists (the last one could also not be defined), the shortest way probably is using reduce
var func = funcName.split(".").reduce(function(p, c) {
return p[c];
}, window);
Split the string so that you can reference one level at a time:
var names = funcname.split(".");
var f = window;
for (var i = 0; i < names.length - 1; i++) {
f = f[names[i]];
}
f[names[names.length - 1]] = function(){...};