rozerro rozerro - 2 months ago 37
Javascript Question

What is wrong with push()?

What is wrong with push() in the next code?

var userInput = {};
var input = '' + $(this).text();
console.log('input=' + input); //success
userInput.push(input); //Uncaught TypeError: userInput.push is not a function


.push is an array method. {} is an object, and you can't push onto objects.

You could either use [] to make userInput an array, or you could keep it an object and add things like this:

var userInput = {};
userInput["myInput"] = input;
// or...
userInput.myInput = input;


var input = '' + $(this).text();

The '' + is unnecessary. It's saying to "add an empty string to this other string", which doesn't do anything. It's like how if you add 0 to 5, you still have 5.

This is fine:

var input = $(this).text();