[英]How do i replace the first number?
I believe that it is simple, but currently it isn't working for me... Look what I need below: 我相信它很简单,但目前对我不起作用...在下面查看我需要的内容:
seed = 9999;
seed[0] = 1;
seed; //now it's returning 9999, but I want 1999
There are another way to do? 还有另一种方法吗?
seed
is a Number, not a string. seed
是数字,而不是字符串。 You either have to use it as string: 您要么必须将其用作字符串:
seed='9999';
seed[0]='1';
console.log(seed)//'1999'
Or you can apply a quick fix: 或者您可以应用快速修复:
seed=9999;
seed-=8000;
console.log(seed)//1999
Update 更新资料
You could also make a class to manage the number i that way: 您也可以通过这种方式创建一个类来管理数字:
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
You can use regex like: 您可以使用正则表达式,例如:
"9999".replace(/[\d]/,"1")
Disclaimer : I am offering an alternate view to problem but of course there is various options to resolve it. 免责声明 :我为问题提供了另一种观点,但是当然有多种解决方案。
try this 尝试这个
seed = 9999;
seed = seed.toString()
seed= 1+seed.substr(1, seed.length);
alert(seed);
As is mentioned above the seed is a number not an array ,so you can't do it as you doing it. 如上所述,种子是一个数字,而不是数组,因此您不能像处理它那样做。 Look at this: 看这个:
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
seed = 9999;
var len = seed.toString().length;
var seedAllDigits = seed % (Math.pow(10,len-1));
var finalSeed = "1" + seedAllDigit;
Somethink like this will do the work.. 像这样的事情会做的..
Hope it make sense 希望有道理
9999%1000 + 1000 * 1 == 1999;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.