arrays - How Do I update Javascript To Return 1 -


how change javascript update one?

well there few of options here. first create prototype object , default value in constructor. i.e.

function foo(name, quantity) {    this.name = name;    this.quantity = !quantity && quantity !== 0 ? 1 : quantity; } 

then, when instantiate array can use new foo(name, quantity); constructor create object, if quantity null or undefined, default value 1 used.

var arr= [new foo('a', 1), new foo('b')]; 

see attached snipped examples on behavior of constructor falsy values.

another option use foreach iterate throught array , reasign value of quantity if null, feels dirty.

i.e.

arr.foreach( x => { x.quantity = !x.quantity && x.quantity !== 0 ? 1 : x.quantity }) 

function foo(name, quantity) {    this.name = name;    this.quantity = !quantity && quantity !== 0 ? 1 : quantity;  }    var foo = new foo('stuff', null);  console.log(json.stringify(foo, null, '\t'));    foo = new foo('stuff', undefined);  console.log(json.stringify(foo, null, '\t'));    foo = new foo('stuff', 0);  console.log(json.stringify(foo, null, '\t'));    foo = new foo('stuff', -1);  console.log(json.stringify(foo, null, '\t'));      var arr= [new foo('a', 1), new foo('b')];  console.log(json.stringify(arr, null, '\t'));

update

ok based on updated code, can create class item, , set value constructor. can define class list can wrap functionality calculating total, , concatenating array of items. check snippet bellow working example.

class item {     constructor(name, price, quantity){        this.name = name;        this.price = price;        this.quantity = !quantity && quantity !== 0 ? 1 : quantity;     }  }    class somelist {      constructor() {          this.items = [];      }        additems(list) {          list.foreach(x => {              this.items.push(x);          });      }        total() {          var t = 0;          this.items.foreach(i => { t += (i.price * i.quantity); });          return t;      }  }    // define array of items, using constructor of item class  var arr = [ new item('a', 100, 1), new item('b', 50) ];    // create list , add items  var list = new somelist();  list.additems(arr);    // total  var total = list.total;    console.log('total '+ list.total);


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -