Javascript 如何替换第一个数字?

Javascript 如何替换第一个数字?,javascript,Javascript,我相信这很简单,但目前它对我不起作用。。。看看下面我需要什么: seed = 9999; seed[0] = 1; seed; //now it's returning 9999, but I want 1999 还有另一种方法吗?种子是一个数字,而不是字符串。您可以将其用作字符串: seed='9999'; seed[0]='1'; console.log(seed)//'1999' 或者,您可以应用快速修复: seed=9999; seed-=8000; console.log(seed

我相信这很简单,但目前它对我不起作用。。。看看下面我需要什么:

seed = 9999;
seed[0] = 1;
seed; //now it's returning 9999, but I want 1999

还有另一种方法吗?

种子是一个数字,而不是字符串。您可以将其用作字符串:

seed='9999';
seed[0]='1';
console.log(seed)//'1999'
或者,您可以应用快速修复:

seed=9999;
seed-=8000;
console.log(seed)//1999
更新

您还可以创建一个类来管理数字i:

function numArr() {
    this.arr = [];
    this.setNum = function (num) {
        this.arr = [];
        while (num > 10) {//while has digits left
            this.arr.unshift(num % 10);//add digit to array
            num = Math.floor(num / 10);//remove last digit from num
        }
        this.arr.unshift(num)//add the remaining digit
    };
    this.getNum = function () {
        var num = 0;
        for (var i = this.arr.length - 1; i >= 0; i--) {//for each digit
            num += this.arr[i] * Math.pow(10, (this.arr.length - 1 - i))//add the digit*units
        }
        return num;
    }
}

var seed= new numArr();
seed.setNum(9960);
seed.arr[0]=1;
console.log(seed.getNum())//1960
seed.setNum(seed.getNum()+1000);
console.log(seed.getNum())//2960

您可以像以下那样使用正则表达式:

"9999".replace(/[\d]/,"1")
免责声明:我为这个问题提供了另一种观点,但当然有多种解决方法

有人认为这样就行了

希望它有意义

试试这个

seed = 9999;
seed = seed.toString()
 seed= 1+seed.substr(1, seed.length);
alert(seed);

正如上面提到的,种子是一个数字而不是数组,所以你不能像做它那样做。看看这个:

var seed = (9999 + "").split(""), // Convert the number to string and split it
    seed = ~~(seed[0] = "1", seed.join("")); // Now you can change the first digit then join it back to a string a if you want to you can also convert it back to number

console.log(seed); // 1999

9999%1000+1000*1==1999

种子不是数组。这是一个数字。延斯,是的,我知道,但有了这个数字就不可能了?不像这样。。。请参阅下面的帖子。。。我得出结论,我将使用字符串而不是数字。谢谢你们的帮助!õ/@user3672624好吧,如果你改变主意,请检查我的更新答案。第三个例子应该是一个模糊代码竞赛的参赛作品,还是什么?@lightness race我的坏,现在更好,简单有效。我一直在寻找“~~”,但我不明白。你能给我解释一下吗?
~
是一种小技巧,如果你需要将字符串转换成数字,你可以使用它。在这种情况下,它并不重要,您可以将其替换为执行相同任务的
parseInt
。更具体地说,
~
是一种称为
NOT
的逐位运算符,用于反转位。你可以在这里找到更多。如果我的回答对你有帮助,请接受。谢谢你在Gary网站上突出显示。。。很难在平板电脑上键入:)变量“seedAllDigits”到“seedAllDigits”
var seed = (9999 + "").split(""), // Convert the number to string and split it
    seed = ~~(seed[0] = "1", seed.join("")); // Now you can change the first digit then join it back to a string a if you want to you can also convert it back to number

console.log(seed); // 1999