简体   繁体   English

Javascript .split()每个字符数的字符串

[英]Javascript .split() a string for each number of characters

I have a variable that holds a number 我有一个包含数字的变量

var simpleNumber = 012345678;

I want to .split() this number and create an array that would be of each 3 numbers 我想.split()这个数字并创建一个每3个数字的数组

the array should look like this 数组应该是这样的

[012, 345, 678]

var splitedArray = simpleNumber.toString().split(/*how do i split this?*/);

it is part of a getRGB("ffffff") function, so i cant know what will be passed in. 它是getRGB(“ffffff”)函数的一部分,所以我不知道将传入什么。

Thanks 谢谢

You can try: 你可以试试:

var splittedArray = "012345678".match(/.../g);

function tridigit(n) {
    return n.toString().match(/.{1,3}/g);
}

Note that if you prefix a number with a zero, it will be interpreted in octal. 请注意,如果为数字前缀为零,则将以八进制形式进行解释。 Octal literals are officially deprecated, but are supported for the time being. 八进制文字已被正式弃用,但目前仍受支持。 In any case, numbers don't have leading zeros, so it won't appear when you convert the number to a string. 在任何情况下,数字都没有前导零,因此当您将数字转换为字符串时它不会出现。

Testing on Safari and FF, numbers with a leading 0 and an 8 or 9 are interpreted in base 10, so octal conversion probably wouldn't be a problem with your specific example, but it would be a problem in the general case. 在Safari和FF上进行测试,前导0和8或9的数字在基数10中解释,因此八进制转换可能不是您的具体示例的问题,但在一般情况下这将是一个问题。

Try this 尝试这个

var num = 123456789+"";// converting the number into string
var x1=num[0]+num[1]+num[2];//storing the individual values
var y1=new Array(x1);// creating a first group out of the first 3 numbers
var x2=num[3]+num[4]+num[5];
var y2=new Array(x2);// creating a second group out of the next 3 numbers
var x3=num[6]+num[7]+num[8];
var y3=new Array(x3);// creating a third group out of the next 3 numbers
var result=y1.concat(y2,y3);// concat all the 3 array
document.write(result);you get the output in the form of array
document.write("<br/>");
document.write(result[0]);
document.write("<br/>");
document.write(result[1]);
document.write("<br/>");
document.write(result[2]);

check the below link for the working example http://jsfiddle.net/informativejavascript/c6gGF/4/ 检查以下链接以获取工作示例http://jsfiddle.net/informativejavascript/c6gGF/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM