TypeError: baseChoiceList.splice is not a function

1.8k views Asked by At

I've worked on this for 4 hours and read many related explanations and tried out several of them. I'm sure I'm missing a simple concept and fix for this error. Your help much appreciated.

ColorChart.setupAnswerChoices();

"setupAnswerChoices": function() {

    var currentChoiceList = sessionStorage.getItem("NE_CURRENT_CHOICE_LIST");
    var baseChoiceList = currentChoiceList.slice();

    console.log ("baseChoiceList " + baseChoiceList);

baseChoiceList 12,17,1,22,27,NCN

consol.log  ("currentChoiceList " + currentChoiceList);

currentChoiceList 12,17,1,22,27,NCN

    var what = Object.prototype.toString;
    console.log("buttonChoice  " + what.call(buttonChoice));

buttonChoice [object Array]

    console.log("baseChoiceList  " + what.call(baseChoiceList));

baseChoiceList [object String]

var buttonChoice = [];

for (var i = 0; i < 5; i++) {
    var randomButtonIndex = Math.floor(Math.random() * (5 - i));
    buttonChoice = baseChoiceList.splice(randomButtonIndex,1);
}

Uncaught TypeError: baseChoiceList.splice is not a function

1

There are 1 answers

0
Norman Breau On BEST ANSWER

sessionStorage (and localStorage) both can only store key/value pairs as strings.

So your code:

var currentChoiceList = sessionStorage.getItem("NE_CURRENT_CHOICE_LIST");
var baseChoiceList = currentChoiceList.slice();

currentChoiceList is not an array. It is a string. baseChoiceList is again, a string, which is a copy of currentChoiceList. (Strings have a slice() method.)

It looks like you actually want to do this:

var currentChoiceList = sessionStorage.getItem("NE_CURRENT_CHOICE_LIST");
var baseChoiceList = currentChoiceList.split(',');

Strings split method accepts a delimiter, to split the string into an array of strings.