Mihkel L.
Mihkel L.

Reputation: 1573

JavaScript empty array

https://stackoverflow.com/a/1234337/1690081

shows that array.length = 0;will empty array but in my code it doesn't

here's an sample:

window.onload = draw;
window.onload = getFiles;
var namelist = [];
function draw(){
    // assing our canvas to element to a variable
    var canvas = document.getElementById("canvas1");
    // create html5 context object to enable draw methods
    var ctx = canvas.getContext('2d');

    var x = 10; // picture start cordinate
    var y = 10; // -------||---------
    var buffer = 10; // space between pictures
    for (i=0; i<namelist.length; i++){
        console.log(namelist[i])
        var image = document.createElement('img');
        image.src = namelist[i];
        canvas.appendChild(image);
        ctx.drawImage(image,x,y,50,50);
        x+=50+buffer;
    }
}
function getFiles(){
    namelist.length = 0;// empty name list
    var picturesFiles = document.getElementById('pictures')
    picturesFiles.addEventListener('change', function(event){
        var files = picturesFiles.files;

        for (i=0; i< files.length; i++){
            namelist.push(files[i].name);
            console.log(namelist)
        }
        draw();
    }, false);

}

after i call getFiles() second time. It doesn't remove the previous list, just appends to it. any idea why?

Upvotes: 1

Views: 3704

Answers (4)

Guffa
Guffa

Reputation: 700272

There is nothing wrong with how you empty the array, so there has to be something else that is wrong with your code.

This works fine, the array doesn't contain the previous items the second time:

var namelist = [];

function draw() {
    alert(namelist.join(', '));
}

function getFiles() {
    namelist.length = 0; // empty name list
    namelist.push('asdf');
    namelist.push('qwerty');
    namelist.push('123');
    draw();
}

getFiles();
getFiles();

Demo: http://jsfiddle.net/Guffa/76RuX/

Edit:

Seeing your actual code, the problem comes from the use of a callback method to populate the array. Every time that you call the function, you will add another event handler, so after you have called the function the seccond time, it will call two event handlers that will each add all the items to the array.

Only add the event handler once.

Upvotes: 0

Esailija
Esailija

Reputation: 140220

You should empty the array in the event handler, not getFiles which is only called once per pageload. It is actually doing nothing because the array is already empty when the page loads.

picturesFiles.addEventListener('change', function(event){
    namelist.length = 0; //empty it here
    var files = picturesFiles.files;

    for (i=0; i< files.length; i++){
        namelist.push(files[i].name);
        console.log(namelist)
    }
    draw();
}, false);

Another problem is that you cannot just set .src to the name of a file. That would make the request to your server for the file.

To really fix this, just push the file objects to the namelist:

namelist.push(files[i]);

Then as you process them in draw, create localized BLOB urls to show them:

var file = namelist[i];
var url = (window.URL || window.webkitURL).createObjectURL( file );
image.src = url;

Upvotes: 1

Tim Joyce
Tim Joyce

Reputation: 4517

If you are using non-numeric indexes then the array will not clear. "...whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted"

Test:
var arr = [];
arr['this'] = 'that';
arr.length = 0;
console.log(arr);
//output ['this':'that']

var arr = [];
arr[0] = 'that';
arr.length = 0;
console.log(arr);
//output []

Upvotes: 0

SDC
SDC

Reputation: 14222

It looks like you're using namelist as a global variable. This would be easier (and would avoid needing to empty it at all) if you passed the new array out of the function as a return value.

ie:

function getFiles() {
    var newNameList = [];
    ..... //push entries here.
    return newNameList;
}

... and then populate namelist from the return value where you call it:

namelist = getFiles();

However, to answer the question that was actually asked:

Instead of setting the length to zero, you can also reset an array simply by setting it to a new array:

namelist = [];

You haven't shown us how you're 'pushing' entries to the list, but I suspect that the end result is that namelist is being generated as a generic object rather than an array object. If this is the case, then setting .length=0 will simply add a property to the object named length with a value of 0. The length property in the way you're using it only applies to Array objects.

Hope that helps.

Upvotes: 0

Related Questions