Peter Richmond Peter Richmond - 3 months ago 9
Javascript Question

Javascript String.Split() Method Giving Strings

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

Answer

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

:)