我找到了一个函数,它使用逗号将数字值转换为数字值,以便轻松地向网页查看器显示大数字。不幸的是,我在网上找到的代码只能成功地使ONE变量等于任何值。由于我必须转换大量变量,因此制作几个不同的函数来实现这一点是不切实际的。我需要帮助修改函数,以便它可以获取一个值及其相应的变量,以便在收到逗号后存储它。
原始代码:
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
//Whatever sole variable you want
= val;
}
我尝试(失败版本)的功能:
//define variables that need to be comma-ed.
var a = 234858912795;
var b = 148582954;
var c = 59928104585125612324;
//Array of variables to be comma-ed
var toComma = [a, b, c];
//Variables to store the value of the numbers with commas.
var aComma;
var bComma;
var cComma;
//Array of variables with comma
var Comma = [aComma, bComma, cComma];
//declare counter variable for the loop later.
var i = 0;
//function to comma numbers
function commaSeparateNumber(val, vari){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
//Here is the problem. Ideally, I want something here so this works, and I can plug in a different variable and value every fraction of a second into this funciton. I could just create multiple DIFFERENT functions, but I have a large number of variables that need to be comma-ed, so I want something like this current setup that works.
vari = val;
}
//Interval calling the function with different numbers.
setInterval(update, 1000);
function update() {
//When the loop successfully cycles through the numbers in the array, it restarted from the first value (0).
if(i = toComma.length - 1){
i = 0}
//Runs function with desired variables.
commaSeparateNumber(toComma[i], Comma[i])
//Increases i to loop through with the next value.
i++
}
//Testing for me to see the number pop up in console. They return as "undefined" everytime.
setInterval(display, 1000)
function display() {
console.log(aComma);
console.log(bComma);
console.log(cComma);
}
答案 0 :(得分:0)
通用函数应返回一个值,而不是设置全局变量。
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
//Whatever sole variable you want
return val;
}
然后你可以调用它并将结果分配给不同的变量:
comma[i] = commaSeparateNumber(toComma[i]);