0

我编写了一个简单的冒泡排序函数,它根据图像名称对 Image 对象数组进行排序。出于某种原因,我的函数在需要时没有交换数组的元素(基本上新分配不起作用)

这是我的代码:

        listOfFiles = event.dataTransfer.files;
        sortImages(listOfFiles);
        function sortImages(listOfFiles)
        {
            var re = /[0-9]/;
            var temp;
            for( var index=0; index < listOfFiles.length ; index++)
            {
                for ( var index2=0; index2 < listOfFiles.length-1 ; index2++)
                {
                    var one = parseFloat(re.exec(listOfFiles[index2].name ));
                    var two = parseFloat(re.exec(listOfFiles[index2+1].name));
                    console.log(one + " : " + two);
                    if (one > two) 
                    {
                        console.log(listOfFiles[index2+1]);
                        console.log(listOfFiles[index2]);
                        //following three lines don't work
                        temp = listOfFiles[index2+1];
                        listOfFiles[index2+1] = listOfFiles[index2];
                        listOfFiles[index2] = temp;


                        console.log(listOfFiles[index2+1]);
                        console.log(listOfFiles[index2]);
                    }
                }
            }
        }
4

1 回答 1

0

问题似乎在于re.exec()返回数组。您需要获取包含匹配字符的第一个索引。请参阅此处的文档:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec 。

以下应该有效:

listOfFiles = event.dataTransfer.files;
sortImages(listOfFiles);
console.log(listOfFiles);

function sortImages(listOfFiles) {
    var re = /[0-9]/;
    var temp;
    for (var index = 0; index < listOfFiles.length; index++) {
        for (var index2 = 0; index2 < listOfFiles.length - 1; index2++) {
            var one = parseFloat(re.exec(listOfFiles[index2].name)[0]); //here
            var two = parseFloat(re.exec(listOfFiles[index2 + 1].name)[0]); //here
            console.log(one + " : " + two);
            if (one > two) {
                console.log(listOfFiles[index2 + 1]);
                console.log(listOfFiles[index2]);
                //following three lines don't work
                temp = listOfFiles[index2 + 1];
                listOfFiles[index2 + 1] = listOfFiles[index2];
                listOfFiles[index2] = temp;

                console.log(listOfFiles[index2 + 1]);
                console.log(listOfFiles[index2]);
            }
        }
    }
}
于 2013-06-28T22:14:52.510 回答