0

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?

Kikehdev
  • 5
  • 2

6 Answers6

1

seed is a Number, not a string. 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
juvian
  • 15,875
  • 2
  • 37
  • 38
1

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.

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
0

try this

seed = 9999;
seed = seed.toString()
 seed= 1+seed.substr(1, seed.length);
alert(seed);
Jens
  • 67,715
  • 15
  • 98
  • 113
0

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
0101
  • 2,697
  • 4
  • 26
  • 34
  • Simple and works. I have looking for the "~~", but I don't understood that. Can you explain me? – Kikehdev May 25 '14 at 01:16
  • The `~~` is a little "hack" that you can use if you need to convert some string to a number. It is not really important in this case and you can replace it with `parseInt` that will do the same job. To be more specific `~` is bitwise operator called `NOT` that inverts bits. You can find out more here http://stackoverflow.com/questions/5971645/what-is-the-double-tilde-operator-in-javascript. Please accept my answer if it did help you. – 0101 May 25 '14 at 09:44
-1
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

Aviad
  • 1,539
  • 1
  • 9
  • 24
-1

9999 % 1000 + 1000 * 1 == 1999;

LogPi
  • 706
  • 6
  • 11