0

我需要您的帮助来修改以下功能。目前,该函数检查字符串中是否存在重复名称。如果找到重复项,它会自动添加 -number 即。123456-2。但是,如果我的字符串已经有一个数字和一个破折号,它只会增加最后一个不应该发生的数字。IE。123456-2012 到 123456-2013,其中字符串应为:123456-2012-2。关于如何纠正它的任何想法?

function test() {

var filename = "123456-2012"

var x = confirm('Duplicate record found!\n\n \''+filename+'\' \n\n rename and add record to the databse as:\n\n \''+new_name(filename)+'\'')

    if (x == true) {

    alert("adding...")
    filename = new_name(filename)
    alert(filename) 
    }

    else { return }

}  

var exists = 0 
function file_exists(name) {
   exists = 1 - exists  
   return exists 
} 

function new_name(suggested) { 

   if (!file_exists(suggested)) { return suggested } 

   var have_index = suggested.match(/^(.+)\-(\d+)$/) 
   var unused_index 
   if (have_index && have_index[2]) { 
      base = have_index[1] 
      unused_index = ++have_index[2] 
   } else { 
      base = suggested 
      unused_index = 2 
   } 

   while (file_exists(base  + "-" + unused_index)) { unused_index++ } 

   return base  + "-" + unused_index

} 
4

1 回答 1

1

在 new_name 函数中进行以下更改

请注意,我已经添加!have_index[2]了 if 条件。

if (have_index && !have_index[2]) { 
      base = have_index[1] 
      unused_index = ++have_index[2] 
   } else { 
      base = suggested 
      unused_index = 2 
   }
于 2012-09-06T18:20:19.487 回答