im really beginner into javascript so I struggle. My problem is - I created objects with constructor with specfic names of objects,
function Food (name, Cal, price, Fat, Carb, Protein, Sugar) {
this.name = name;
this.Cal = Cal;
this.price = price;
this.Fat = Fat;
this.Carb = Carb;
this.Protein = Protein;
this.Sugar = Sugar;
}
//bul
var bulPs = new Food("Bul"+" "+"Psz",120,3.50,36,80,45,78);
var bulSz = new Food("Bul"+" "+"Sez",140,2.90,34,75,33,68);
var bulBr = new Food("Bul"+" "+"bric",136,2.89,39,67,41,75);
var bulMa = new Food("Bul"+" "+"Man",157,3.20,42,56,36,78);
I have checkboxex, and when I click them i push chosen items (their id into array). Id of inputs are same as objects
Eg var bulMa and the id of this item is "bulMa".
When I try to call object's values with arrays index, it shows undiefined. Can someone tell me whats wrong ? Its because its outside of function fodd? Which part of JS core I should understand to handle those problems. Thanks
var zaz = [];
var inputs = document.getElementsByTagName('input');
for (var i=0; i< inputs.length; i++)
{
inputs[i].onfocus = function() {
zaznaczone.push(this.id);
console.log(zaz);
console.log(zaz[0].name);
};
}
Your array is called zaz, but you are pushing into zaznaczone.
Also zaz[0].name will be undefined; zaz[0] is the Id of the element and thus the name of your object.
var zaz = [];
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onfocus = function() {
zaz.push(this.id);
console.dir(zaz);
};
}
Related
I have a need for referencing an array name out of other variables values. Below is a simple program that doesn't push the value into an array. I was hoping someone could determine why. There is no runtime error but when you print the array it has not been pushed. I am creating a 4 person card game that currrently works by having a 2D array with 4 players. I want to deal the cards to P0cards P1Cards.... instead of the 2D players[[],[],[],[]] array.
My idea of using $p{i}.push(card) is not working
class Card{
constructor(suit, value){
this.value = value;
this.suit = suit;
}
}
let deck = [];
let players = [[],[],[],[]];
var p0Cards = [];
var p1Cards = [];
var p2Cards = [];
var p3Cards = [];
function deal(){
//players 1,2,3,4
for(let i = 0; i < 4; i++){
//cards 1,2,3,4,5,6
for(let j = 0; j < 6; j++){
let card = deck.pop();
//players[i].push(card);
`$p{i}.push(card)`; //this is what I would like to do.
}
}
}
Can you make your arr part of an object? Then you can access it with the use of a string.
let myVars = {}
myVars.arr = []
let x = 'arr';
myVars[x].push(2);
myVars.arr.push(3);
console.log(myVars.arr);
// myVars.arr = [2, 3]
I have following code:
var students = [];
for(var i = 0; i < classes.length; i++) {
var student = {};
student = classes[i].student;
student.teacher = classes[i].teacher;
students.push(student);
}
Somehow the students will print same object for all its contents, although I have put var student = {}; inside the loop, thus it must not refer to same reference.
Anyone has idea why this happens?
You put student = {} inside the loop, then on the line immediately following that one you overwrote that by assigning student = classes[i].student.
If the intention is to make a copy of whatever classes[i].student is you can use the Object.assign() method:
var student = Object.assign({}, classes[i].student);
In context:
var students = [];
for(var i = 0; i < classes.length; i++) {
var student = Object.assign({}, classes[i].student);
student.teacher = classes[i].teacher;
students.push(student);
}
(Note that Object.assign() doesn't do a deep copy - I'm not sure if that matters because you haven't shown what the classes array structure is.)
You could also use the .map() method instead of an explicit for loop:
var students = classes.map(function(c) {
var student = Object.assign({}, c.student);
student.teacher = c.teacher;
return student;
});
I'm new to javascript. So this question might not be good.
var arrQue = new Array(10);
for (var i = 0; i < 10; i++) {
arrQue[i] = new Array(6);
}
This code works perfectly but I wanted to know without giving the array size, how can I make something like this (the following code doesn't work):
var arrQue = new Array();//don't know the size
for (var i = 0; i < arrQue.length; i++) {
arrQue[i] = new Array();//don't know the size
}
And also the code contains two times creating new array. Is there easier or best way to do that creating multiple array?
And later I've to access like this:
arrQue[0][6] = "test";
arrQue[23][3] = "some test";
I found this method but think wrong somehow?
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var arrQue = [];
var size = Object.size(arrQue);
for (var i = 0; i < size; i++) {
arrQue[i] = [];
var nextSize = Object.size(arrQue[i]);
}
var arrQue = [];
for (var i = 0; i < length of your inputs; i++) {
arrQue.push(input);
}
Take a look here
Check out the Array Object Methods there.. that's all the stuff you need.
You can have arrays,arrays of objects... etc..depending upon your requirement.
var arrQue = [];
for (var i = 0; i < 10; i++) {
arrQue.push(input);
}
you might be looking for the push method:
var arr = [];
arr.push(your value);
How to add values to an empty array? I have tried the following but it is not working:
var student = [{}];
for (var i = 0; i < 5; i++) {
student[i].name = i;
student[i].id = "1";
student.push(student[i]);
}
var a = JSON.stringify(student);
alert(a);
It give output 6 time repeated last values not 5 time :
'[{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"}]'
var student = [{}];
This creates a javascript array containing one empty object
student[i].name = i;
student[i].id = "1";
For i = 0, this alters that empty object.
student.push(student[i]);
You then push that altered object to the array it already exists in. You now have two identical values in the array.
Two items after first push. This is repeated five times.
Pushing an item adds it to the array. There's usually no point in pushing an element that's already in the array. Create a new object and push that. The array doesn't have to be pre-populated with an empty object to modify.
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
name: i,
id: '1'
});
}
In your original code, you are setting the object at student[i]'s values, then just pushing it again onto the array, then setting those values all over again.
You need to push a new object each time:
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
id: i,
name: i
});
}
var a = JSON.stringify(student);
alert(a);
You are using the same name for the list and the new object. When you change the name of the list to students, your problem is fixed. Solution below:
var students = [{}];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
try ;
var students = [];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
Your array is not empty. It already contains an object. Maybe the problem is easier to see if we put the object in an extra variable and omit the the loop:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj.name = 2;
student.push(obj)
The question is: How many objects are we creating here? The answer is one, namely var obj = {};. We then add some properties to the object (name) and add it to the array (student.push(obj)).
What comes next is crucial: We change the existing properties of the object and assign different values to it. Then we add the object to the array again. Even though student contains two elements, but they refer to the same value (which can be easily verified with student[0] === student[1]).
If you want to create an array of different objects, you have to create those objects. In our example this would be:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj = {}; // <- create a new object
obj.name = 2;
student.push(obj)
For your code that means that you have to create a new object in each iteration of the loop, not just one outside of it.
Reading material about arrays and objects:
Eloquent JavaScript - Data structures: Objects and Arrays
MDN - Working with objects
MDN - Array object
Since you are pushing object, its reference change every time to current value so at last it shows the output as last value.
Try this
var student = [{}];
for (var i = 0; i < 5; i++) {
var obj = new Object();
obj.name = i;
obj.id = "1";
student.push(students);
}
var a = JSON.stringify(student);
alert(a);
I'm trying to create a 3 dimensional array dynamicall in javascript based on a flat array of objects. after looping through the array, the array seems empty. If I print while in the loop, it seems to work, but then it seems to be gone and I want to return this to the caller. Help ?
//init the 3d array ??
this.teams = [];
for(var i = 0; i < sportsStandings.length; i++) {
var item = sportsStandings[i];
if(!this.teams[item.league])
this.teams[item.league] = new Array();
if(!this.teams[item.league][item.division])
this.teams[item.league][item.division] = new Array();
this.teams[item.league][item.division][this.teams[item.league][item.division].length]
= new Team(item.teamName, item.wins, item.losses);
console.log(this.teams); //this prints properly, and i see the 3d array grow
}
console.log('second' + this.teams); //this prints nothing
I cleaned up the code a bit, there is a couple of other ways to write it.
this.teams = [];
var teams = this.teams;
for(var i = 0; i < sportsStandings.length; i++) {
var ss = sportsStandings[i],
league = ss.league,
division = ss.division,
teamName = ss.teamName,
wins = ss.wins,
losses = ss.losses;
if (!teams[league]) {
teams[league] = {};
teams[league][division] = [];
} else if (!teams[league][division]) {
teams[league][division] = [];
}
var newTeam = new Team(teamName, wins, losses);
teams[league][division].push(newTeam);
}