我编写了一个简单的冒泡排序功能,可根据图像名称对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]);
}
}
}
}
答案 0 :(得分: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]);
}
}
}
}