Javascript push()有什么问题?

Javascript push()有什么问题?,javascript,Javascript,下一段代码中的push()有什么问题 var userInput = {}; var input = '' + $(this).text(); console.log('input=' + input); //success userInput.push(input); //Uncaught TypeError: userInput.push is not a function 您正在声明一个对象并尝试推送,它应该是一个数组。试着这样宣布 var userInput = []; .push是

下一段代码中的push()有什么问题

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

您正在声明一个对象并尝试推送,它应该是一个数组。试着这样宣布

var userInput = [];

.push
是一种数组方法
{}
是一个对象,您不能
推到对象上

您可以使用
[]
userInput
设置为数组,也可以将其保留为对象并添加如下内容:

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

“”+
是不必要的。它的意思是“在另一个字符串中添加一个空字符串”,这并没有任何作用。这就像如果你把
0
添加到
5
,你仍然有
5

这很好:

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

试试这个。你不能将对象推送到数组中

var userInput = [];
var input = '' + $(this).text();
console.log('input=' + input); //success
userInput.push(input); 

userInput是一个对象,push是一种数组方法SideNote:可以在对象上使用数组方法,即:
Array.prototype.push.call(userInput,'foo')
。不过,你不太可能需要这个。改用数组。
var userInput = [];
var input = '' + $(this).text();
console.log('input=' + input); //success
userInput.push(input);