Given the following data:
var x = 3
var number = 0621
How can I enumerate through number and try to find x digit in that number? If x exists in number, remove that number.
Can a integer be treated as an array?
Be careful. Number will be 401 as soon as you have assigned 0621 to it because of octal issues - extra tricky with the invalid octal numbers 08 and 09.
Instead make number a string and you can use charAt or indexOf:
function chop(numString,num) { var pos = numString.indexOf(""+num); if (pos ==-1) numString+=num; else numString = numString.slice(0, pos) + numString.slice(pos+1); return numString; } var num = 0621; console.log("Octal",num); // to show the octal issue // better: console.log(chop("0621", 2)); console.log(chop("0621", 3));
Would be some like this?
var x = 3 var number = 0621; var _new = ''; for (var t = 0; t < String(number).length; t++) { if (String(number).charAt(t) !== String(x)) _new += String(number).charAt(t); } console.log('and new', +_new);
Can a integer be treated as an array?
You can cast your number
as a string
then split it, this will give you an array.
How can I enumerate through number and try to find x digit in that number? If x exists in number, remove that number
Now you can loop over the digits array to check if your inputted x
is among them.
This is what you need:
var x = 3 var number = 5783; //This will give you an array with your digits var arr = (String(number)).split(''); if (arr.indexOf(String(x)) === -1) { arr.push(x); } else { arr = arr.map(function(n) { return n == x ? '' : n; }); } console.log(arr.join(''));
Note:
Note that leading 0
in a number
will give you unexpected resluts, so be careful about that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.