I'm trying to do something like drawing cards.
I have an array with 52 elements (deck[]), and I want to remove the first 13 elements and put them into another array, lets say player1[].
Then remove the next 13 elements and put them into player2[]...and so on.
I did this:
var deck = [], player1 = [], player2 = [], player3 = [], player4 = [];
function distributeCards(){
for(var i = 1; i < 5; i++){
for(var j = 0; j < 13; j++){
player+i.push(deck.shift(j));
}
}
}
The array variables are declared outside, because I have to access them in other functions.
It says player is not defined...how should I write this?
You can't make up variable name with that. Instead, you should consider using array to store player's card, so you can dynamically reference each of the player's deck like this:
var deck = [];
var numOfPlayers = 4;
var players = new Array(numOfPlayers);
function distributeCards(){
for(var i = 0; i < numOfPlayers; i++){
players[i] = [];
for(var j = 0; j < 13; j++){
players[i].push(deck.shift(j));
}
}
}
Related
I've to do a strange thing and I don't know if is possible.
Let assume I've one aray
MasterArray = [1,2,3,4];
Now for each MasterArray item I need to have multiple insertion, for example under the item 1 I've to push N value, for example the MasterArray[0] must have this correlations
5,8,3,9 ...
This for any items on MasterArray.
My first idea is to create a new array one for each MasterArray items, something like this
var newobject = X;
for (i = 0; i < MasterArray.length; i++) {
Arr[i] = push the newobject ;
}
But I don't think that is a good way!
The purpose it to have a kind of correlated array.
MasterArray[0] is correlated to another array [5,8,3,9, ...]
MasterArray[1] is correlated to another array [5,6,7,1, ...]
MasterArray[2] is correlated to another array [7,45,23,2, ...]
And so on
I hope to have explained myself
Just create a 2D array in this way:
var myArray = new Array(5); // For example 5;
for (var i = 0; i < myArray.length; i++) {
myArray[i] = new Array(10);
}
Or, if you don't need to specify any size:
var myArray = new Array(5); // For example 5;
for (var i = 0; i < myArray.length; i++) {
myArray[i] = [];
}
EDIT:
For manipulate you just need to use innested loops:
for (var i = 0; i < myArray.length; i++) {
for (var j = 0; i < myArray[i].length; j++) {
myArray[i][j] = x; // where x is some variable
}
For add elements in the back just use .push() method:
myArray[0].push(5);
I'm trying to build a list of Urls. The structure is like this:
http://somedomain.com/game_CATEGORY?page=NUMBER.
I have an array of game categories, ranging from action games category to word games category.
I have an array of numbers, 1 through 20.
I have pieces of the url saved as strings.
I've been trying for a day to combine them in this way:
cats = ["action","adventure","arcade","board","card","casino","casual","educational","family","music","puzzle","racing","role_playing","simulation","sports","strategy","trivia","word"],
nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
urlString1 = "http://example.com/game_",
urlString2 = "?page=",
madeUrl1 = [],
x = 1, // counter for page numbers
madeUrl2 = [];
for (var i = 0; i < cats.length; i++) {
madeUrl1.push(urlString1+cats[i]+urlString2);
};
for (var i = 0; i < madeUrl1.length; i++) {
madeUrl2.push(madeUrl1[i]+x);
x++;
};
console.log(madeUrl2);
This gets me partially there. But its printing out one number per category. I need each category printout to have ALL 20 numbers added, then move on to the next category.
You'd need to nest another for loop inside your second one. Something like:
for (var i = 0; i < madeUrl1.length; i++) {
for (int j = 0; j < nums.length; j++) {
madeUrl2.push(madeUrl1[i]+nums[j]);
}
};
That way you're iterating through the base URLs you prepared in madeUrl1, and then for each of those you're iterating through each number you have in the array.
If the numbers are simply sequential from 1 to 20, you don't even need the nums array:
for (var i = 0; i < madeUrl1.length; i++) {
for (var x = 1; x <= 20; x++) {
madeUrl2.push(madeUrl1[i]+x);
}
};
And the whole thing could be accomplished with a single nested for loop:
for (var i = 0; i < cats.length; i++) {
for (var x = 1; x <= 20; x++) {
madeUrl1.push(urlString1+cats[i]+urlString2+x);
}
};
You can use the code below:
cats = ["action","adventure","arcade","board","card","casino","casual","educational","family","music","puzzle","racing","role_playing","simulation","sports","strategy","trivia","word"],
nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
urlString1 = "http://example.com/game_",
urlString2 = "?page=",
madeUrl1 = [],
x = 1;
for (var i = 0; i < cats.length; i++) {
for (var j = 0; j < nums.length; j++) {
madeUrl1.push(urlString1+cats[i]+urlString2+nums[j]);
x++;
};
};
console.log(madeUrl1);
What we did here, is first nesting our loops. E.g., it will first loop through the first array, and when it arrives at it first item, in this case a category, it will run the nested loop 20 times, appending each number to the page. After done, it continues to the second category and so on.
I'm working on a codecademy.com lesson on arrays. I'm supposed to write nested loops to put each card of every suit in a deck of cards in an array.
I'm really messing this up. This is one combination that I've tried that doesn't work. The only indication that I have that I'm sort of close is that it returns "52" so at least 52 objects are going into the array. can anyone point out what I'm doing wrong?
//array 1: the suits
var suits = ["clubs","hearts","diamonds","spades"];
//array 2: the ranks
var ranks = [2,3,4,5,6,7,8,9,10,"J","Q","K","A"];
//using for loops, modify the "deck" array so that it becomes a
//two-dimensional array that stores every card in the deck;
//e.g. [1, "clubs"], [2, "clubs"],etc...["A", "spades"]
var deck = [];
for(i = 0; i < suits.length; i++){
for (j = 0; j < ranks.length; j++){
var cardArray = [];
cardArray[0] = suits[i];
cardArray[0][0] = ranks[j];
deck.push(cardArray);
}
}
Each iteration, a new array is being added to deck that looks like the following:
cardArray: [ [ ranks[j] ] ]
When cardArray[0][0] is set, it is overwriting cardArray[0] as an array with index 0 containing ranks[j]. Instead, set cardArray[0] to suits, and cardArray[1] to ranks.
cardArray[0] = suits[i];
cardArray[1] = ranks[j];
deck.push(cardArray);
This results in:
for (var i = 0; i < suits.length; i++){
for (var j = 0; j < ranks.length; j++){
var cardArray = [];
cardArray[0] = suits[i];
cardArray[1] = ranks[j];
deck.push(cardArray);
}
}
You should use a var declaration for your loop counter. Your problematic code is
cardArray[0] = suits[i];
cardArray[0][0] = ranks[j];
which does things like
var foo = "clubs";
foo[0] = "J";
which obviously does not work. I think what you want is
var deck = [];
for(var i = 0; i < suits.length; i++){
var cardArray = [];
for (j = 0; j < ranks.length; j++){
var twoCards = [];
twoCards[0] = suits[i];
twoCards[1] = ranks[j];
cardArray.push(twoCards);
// // or the same thing as this loop body, shorter:
// cardArray.push([suits[i], ranks[j]]);
}
deck.push(cardArray);
}
This may be a fairly simple question but it's just not working for me no matter how many times I change the for loop around. So how would you loop through this array using a for loop in JavaScript?
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
This is what I have and it's not working. I used an alert to just test out the result but it's not even returning anything.
for(itemSet in fielditems){
var itemSetValues = fielditems[itemSet];
for(set in itemSetValues){
var itemValue = itemSetValues[set];
for(value in itemvalue){
alert(itemValue[value]);
}
}
}
What am I doing wrong?
Don't use for() with in for arrays. It's for object properties. Use the standard format instead.
Demo: http://jsfiddle.net/ThinkingStiff/EVWch/
Script:
var fielditems =[
[["News Tips"],["Opinions"],["MedMinutes"]],
[["Yes"],["No"],["Maybe"]],
[["How"],["Why"],["When"]]
];
for( var itemIndex = 0; itemIndex < fielditems.length; itemIndex++ ){
var itemSetValues = fielditems[itemIndex];
for(var setIndex = 0; setIndex < itemSetValues.length; setIndex++ ){
var itemValue = itemSetValues[setIndex];
for(var valueIndex = 0; valueIndex < itemValue.length; valueIndex++ ){
alert(itemValue[valueIndex]);
};
};
};
Firstly, console is your friend. You get error ReferenceError: itemvalue is not defined because javascript is case sensitive. Change itemvalue in the most nested loop to itemValue.
Secondly, if you want iterate thorugh an array, you should use for-loop instead for-in-loop
Don't use for-in loops on arrays
Don't use (running) variables without declaring them as local
for (var i=0; i<fielditems.length; i++) {
var itemSetValues = fielditems[i];
for (var j=0; j<itemSetValues.length; j++) {
var itemvalue = itemSetValues[j]; // notice the case
for (var k=0; k<itemvalue.length; k++) {
alert(itemvalue[k]);
}
}
}
for..in is for objects ({}), not for arrays ([]).
You need to use a standard for loop.
for(var i = 0, iLen = fielditems.length; i < iLen; i++){
var iItem = fielditems[i];
for(var j = 0, jLen = iItem.length; j < jLen; j++){
var jItem = iItem[j];
alert(jItem[0]); // you can also add another loop here, if this will have more elements
}
}
NOTE:
for(var i = 0, iLen = fielditems.length; i < iLen; i++)
is better than:
for(var i = 0; i < fielditems.length; i++)
because fielditems.length isn't requested each loop, just once at the start.
function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed