0

So I have an interesting issue with using String.split() in Google Chrome in a recent, quick Javascript algorithm. I'm dealing with a pretty large object where I want to look at each key of the object, check it for qualities, then operate on the name of the key string if it matches (trying to increment for each word in the name).

The code below accounts for the error, and assumes the existence of cardData (a variable declared in a separate script in HTML, equivalent to var cardData=(Giant object here), specifically the object in AllCards.json located at mtgjson.com.

When I console.log the name (or typeof name), it seems to be returning a comma-delineated string, and not an actual Javascript array. This error does reproduce in an alternate tab with a dataset of only 3 with the same algorithm. I'm curious to see if anyone else has seen this issue thus far, else has some insight I might be missing in this case. Thanks!

Sample input and code:

var cardData = {
    "Shivan Dragon": {
        "types": ["Creature"]
    }, 
    "Mimeoplasm": {
        "types": ["Creature"]
    }, 
    "This Is A Card Name": {
        "types": ["Creature"]
    }
};

var totalNameLength = 0;

var alreadyCheckedNames = {};

for (var key in cardData){
  if ((cardData[key]["types"] && cardData[key]["types"].indexOf("Creature") === -1) || (cardData[key]["supertypes"] && cardData[key]["supertypes"].indexOf("Legendary") !== -1)){
      delete cardData[key];
  } 
  else {

    if (!alreadyCheckedNames[key]){

      var name = String.prototype.split.call(key, " ");

      totalNameLength++;
      alreadyCheckedNames[key] = cardData[key];

      for (var i = 0; i < name.length; i++){
        if (name[i] === ","){
          totalNameLength++;
        }
      }

    console.log(name);
    }
  }
}

console.log(totalNameLength);

Sample Console Output:

Shivan,Dragon
Mimeoplasm
This,Is,A,Card,Name
8
JJJ
  • 32,902
  • 20
  • 89
  • 102
  • 1
    Why are you calling `String.prototype.split` instead of just splitting the key? (If this had been in a function as is appropriate it looks like it should work.) – Dave Newton Aug 18 '16 at 17:27
  • It was a temporary change to verify it was being split correctly. Still functional either way, but it was indeed an issue with window.name polluting the space. – Peter Richmond Aug 18 '16 at 17:31

1 Answers1

0

I think I found the problem … This doesn't work:

for (var key in cardData){
    var name = key.split(" ");
    console.log(name);
}

But this does:

for (var key in cardData){
    var card_name = key.split(" ");
    console.log(card_name);
}

:)

Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34