填充数组后为空元素

时间:2018-10-04 15:27:15

标签: javascript html

我有一个名为files_url的数组。我是这样填写的:

var files_url = new Array(filesnb);
var files_name = new Array(filesnb);
for (var i = 0, k = 0; i < filesnb; i++) {
    files_name[i] = selectedFile[i].name;
    const uploadTask = storageRef.child(`${selectedFile[i].name}`).put(selectedFile[i]); 
    uploadTask.on('state_changed', (snapshot) => {
        var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');
        }, (error) => {
            console.log(error);
        }, () => {
        uploadTask
            .then(snapshot => snapshot.ref.getDownloadURL())
            .then((url) => {
                //Here is the part where i fill my array "files_url"
                for (var len = 0; len < i; len++) {
                    if (check_right_url(files_name[len], url) === 0) {
                        files_url[len] = url;
                        console.log(i);
                        console.log(len);
                        break;
                    }
                }
            })
    });
}

当我console.log(files_url)时,可以在阵列上看到正确的信息,但是当我尝试进行console.log(files_url[0])时,它会向我显示undefined。为什么?如何检索数组的内容?

这是一些屏幕:

当我做console.log(files_url)时:

enter image description here

enter image description here

当我做console.log(files_url[0])时:

enter image description here

1 个答案:

答案 0 :(得分:2)

如果“正确的URL”不是第一个,则将其放置在数组中不是0的索引处,因此files_url[0]将是undefined (您的屏幕快照将其显示为“空插槽”;当您读取一个空插槽时,将获得值undefined)。像这样:

var files_url = [];
files_url[1] = "file"; // Note 1, not 0
console.log(files_url[0]);

您可能想要:

files_url.push(url);

files_url[files_url.length] = url;

相反。