2

i want to build an object using this code

$("input").bind("keydown",function(e){
 var code = (e.keyCode ? e.keyCode : e.which);
 if (code == 13){
  var guess = $("input").val();
  guess = guess.split(" ");
  var oGuess = {};
  for (var x = 0; guess.length ; x++){
   oGuess[x] = oGuess[x] = {"text": guess[x]};
  }
  $("input").val("");
 }
});

this actually crashes my browsers(latest stable ff and chrome) upon hitting enter. heres the jsfiddle http://jsfiddle.net/kfqJC/1/

i need the object to be something like this

oGuess = {
"1": { "text" : string}
"2": { "text" : string}
...
}

what am I missing here?

1
  • for (var x = 0; guess.length ; x++) <= should be x < guess.length Commented Nov 5, 2011 at 15:43

1 Answer 1

3

Your loop never terminates. If guess has one element or more, guess.length will always evaluate to true.

I assume you want

for (var x = 0; x < guess.length ; x++){
//              ^^^      

Also, what is this for?

oGuess[x] = oGuess[x] = {"text": guess[x]};

Just write

oGuess[x] = {"text": guess[x]};

And if you want the properties start with 1, you have to write

oGuess[x+1]

thought I don't see any advantage of using an object over an array in this case.

Sign up to request clarification or add additional context in comments.

6 Comments

means "I guess you want for (var x = 0, len = guess.length; x < len; x++) { "
Why not use oGuess.push({"text":guess[x]}); ?
@Mithon: oGuess is an object, not an array, and therefore does not have a method push, unless you define it which is not the case here.
@Felix Kling: Of course you'd also have to change the initialization to var oGuess = []; but I didn't think I'd have to spell that out. Just seems weird to keep it an object when it's used like an array.
That's what I meant with I don't see any advantage of using an object over an array in this case. I don't know why the OP wants this.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.