简体   繁体   中英

Creating variables from array

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);
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM