/    Sign up×
Community /Pin to ProfileBookmark

Simple js function not working

Hi all,

I have a problem with a simple javascript function that I am trying to get to work. My aim is to get the array [B]guess[/B] to output the indices of the string [B]alphabet[/B]. At the moment I am getting all -1 values. Here is the code, your help would be appreciated:

N_ALPHA = 6;
N_CHOICES = 4;
ALPHABET = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

var alphabet = ALPHABET.substring(0, N_ALPHA);

function guessStrToArr(inStr)
{

var i;
var guess = new Array();
var myString = inStr;
var myArray;

myString = myString.toUpperCase();
//alert (myString);
myArray = myString.split();
//alert (myArray);

for (i = 0; i < N_CHOICES; i++) {
guess[i] = alphabet.indexOf(myArray[i]);
}
return guess;

}

Thanks

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@OakbardauthorJan 27.2012 — Please disregard, I have worked out that it was because I wasn't using "" in the split function.
Copy linkTweet thisAlerts:
@bionoidJan 27.2012 — Can you give me an example of an input you would pass to [B]guessStrToArr[/B], and the result you expect from it.

I took a guess at it anyway:

[CODE]var N_ALPHA = 6;
var N_CHOICES = 4;
var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var alphabet = ALPHABET.substring(0, N_ALPHA);

function guessStrToArr(inStr)
{
var
myArray = inStr.toUpperCase().split(''),
guess = [], i;

for (i = 0; i < myArray.length; i++) {
guess[i] = alphabet.indexOf(myArray[i]);
}
return guess;
}

alert(guessStrToArr('cat')); // 2,0,-1[/CODE]
×

Success!

Help @Oakbard spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...