简体   繁体   中英

For-Loop using function from a Constructor

I'm going through Codecademy's lesson on building a Blackjack game with Javascript.

I'm having trouble coming up with code to put in the for-loop. I'm supposed to write a "score" method in the Hand constructor. It should loop over all of the cards in the Hand, summing up the result of the "getValue" call to each and return that sum.

Can someone help me out please? Thank You.

Here's my attempt, the relevant code is inside the for-loop at the bottom:

// Card Constructor
function Card(s, n) {
  var suit = s;
  var number = n;
  this.getSuit = function() {
    return suit;
  };
  this.getNumber = function() {
    return number;
  };
  this.getValue = function() {
    if (number >= 10) {
      return 10;
    } else if (number === 1) {
      return 11;
    } else {
      return number;
    }
  };
};

//deal function
var deal = function() {
  var randNum = Math.floor(Math.random() * 13) + 1;
  var randSuit = Math.floor(Math.random() * 4) + 1;
  console.log(randNum, randSuit);
  return new Card(randSuit, randNum);
};


function Hand() {
  var handArray = [];
  handArray[0] = deal();
  handArray[1] = deal();
  this.getHand = function() {
    return handArray;
  };
  this.score = function() {
    var sum;
    for (var i = 0; i < handArray; i++) {
      sum += handArray[i].getValue;
      return sum;
    }
  };
};

Well something like this should work :

this.score = function() {
  return handArray.reduce( function( memo, val){
    return memo + val.getValue();
  });
};

I think you need to return the score, outside of the loop, like so:

this.score = function() {
  var sum;
  for (var i = 0; i < handArray; i++) {
    sum += handArray[i].getValue();
  }
  return sum;
};

This fixed it. Thanks for your help!

this.score = function(){
    var sum =0;
    for(var i =0; i<handArray.length; i++){
        sum += handArray[i].getValue();
     }; 
    return sum;
};

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