user3346088
user3346088

Reputation: 109

error with pushing a new item into an array

imgFileName = new Array();
imgFileName = imgFileName.push(escape(theFile.name));

assume the theFile.name change every time a function executed.

I console log imgFilename and it return 1?

what I want is storing values into an array by push.

Upvotes: 0

Views: 89

Answers (3)

John S
John S

Reputation: 21482

The array .push() method returns the length of the array after the element is added to the array, so you are changing the imgFileName variable to hold the length of the array.

You could do:

var imgFileNames = [];
imgFileNames.push(escape(theFile.name));

And if you need to work with the file name:

var imgFileNames = [];
var fileName = escape(theFile.name);
imgFileNames.push(fileName);

Just to be clear though, you are not going to want to create the array every time right before you push a file name onto it. You will want to create it once.

Upvotes: 2

Sarath
Sarath

Reputation: 608

you just push the value no need to assign it , push method returns the new length of the array

if you try to do like imgFileName=imgFileName.push(escape("name"));

imgFileName will always returns the length

imgFileName = new Array();
imgFileName.push(escape(theFile.name));
console.log(imgFileName);

Upvotes: 0

Ryan
Ryan

Reputation: 14649

You're reassigning the imgFileName when you assign it the operator =;

imgFileName = new Array();
imgFileName.push(escape(theFile.name));

Fiddle

Upvotes: 0

Related Questions