Home > Back-end >  NodeJS TypeError: Cannot read properties of undefined (reading '0')
NodeJS TypeError: Cannot read properties of undefined (reading '0')

Time:12-25

I get the enemyCards from the frontend and it is an array, with 990 x 7 poker cards. The sortCardOrder function just take the cards in order so i can search in my datas.

This is my NodeJS code:

import fs from 'fs';
import G from 'generatorics';

export default function findEnemyStrongest(enemyCards) {
  let eCombination = enemyCards.enemyCards;
  let result = [];
  for(const comb of eCombination){
  result.push(findStrongest(comb));
  }
  console.log(result);
}

function createCombinations(enemyC){
  let combine = enemyC;
  let onlyName = [];
  let allCombinations = [];
  for (let card of combine){
    onlyName.push(card.name);
  }
  for (let comb of G.combination(onlyName, 5)){
    allCombinations.push(comb.slice());
  }
  return allCombinations;
}

function findStrongest(combi){
    let rawdata = fs.readFileSync('data.json');
    let strenghtOrder = JSON.parse(rawdata);
    let combinations = createCombinations(combi);
    let combinationsName = [];
    let ordered = "";
    let result = [];

    for(let combination of combinations){
      let nameString = "";
      let colors = {'C': 0, 'S': 0, 'H':0, 'D':0};
      for(let card of combination){
        nameString  = card[0];
        colors[card[1]] =1
      }
      ordered = sortCardOrder(nameString, colors);
      combinationsName.push(ordered);
      console.log(combinationsName)
      result.push(strenghtOrder.cardStrenght[ordered]);
    }
    return Math.min(...result);
  }

  function sortCardOrder(string, colors){
    }

Can anyone know what is the problem?

CodePudding user response:

We can infer this line is causing the error:

        nameString  = card[0];

It is requesting the 0 property of the card variable, but card is undefined. Card gets its value from combination. Print out combination to see if it has undefined values.

...
for(let combination of combinations){
   console.log(combination)
...

Combination gets it value from combinations, which comes from comb. Print out the values of comb.

...
for (let comb of G.combination(onlyName, 5)){
   console.log(comb)
...

Keep going backwards until you find the source of the 'undefined' value. Without seeing the original source data (from G), stepping through the code is the only way to find the error source.

  • Related