很抱歉这个菜鸟问题,但是我对javascript真的不满意。我有String列表,其末尾有数字:


测试001
测试002
测试003


我想增加字符串末尾的数字。

到目前为止我尝试过的是:

var test = 'Test-001';
var lastNum = test.split('-');

console.log( lastNum[1] + 1 ); // result: 0011
console.log( Number( lastNum[1] ) + 1 ) // result: 2


我要做的是产生结果(Test-001到Test-999)。

先感谢您

最佳答案

您接近了....但是请尝试以下操作:

var test = 'Test-001';
var pieces = test.split('-');
var prefix = pieces[0];
var lastNum = pieces[1];
// lastNum is now a string -- lets turn it into a number.
// (On older browsers, the radix 10 is essential -- otherwise it
// will try to parse the number as octal due to the leading zero.
// the radix is always safe to use and avoids any confusion.)

lastNum = parseInt(lastNum, 10);
// lastNum = +lastNum is also a valid option.

// Now, lets increment lastNum
lastNum++;

// Now, lets re-add the leading zeros
lastNum = ("0000" + lastNum).substr(-3);

09-19 22:58