如果param有值并且params末尾有点,如何在每个params后面添加逗号分隔符



例如,我们有3个参数

function test(a,b,c){
console.log(a + ',' + b + ',' + c +'.')
}
test('a','b','c')

将打印

> a, b, c.

但在b为空的情况下,结果将显示为两个逗号,如

test('a','','c')

将打印

a,,c.

我们可以像检查一样改进每个var

function test(a,b,c){
console.log(a + (a?',':'') + b + (b?',':'') + c +(c?'.':''))
}

所以现在

test('a','','c')

将打印

a,c.

看起来不错,但当我们只有b 时

test('','b','')

将打印

b,

现在我们必须检查值ab是否存在,并且没有c来打印'.'

和复杂性增加,但如果我们有n个变量,如何更容易地解决

预期结果是:

test('a','b','c') => a, b, c.
test('a','b','') => a, b.
test('a','','') => a.
test('','b','c') => b, c.
test('','b','') => b.
test('','','') => 

您可以过滤并使用。。。静止参数

const isParm = prm => prm !== "" && prm !== undefined && prm !== null;
const test = (...theArgs) => {
const list = theArgs.filter(parm => isParm(parm)); 
if (list.length > 0) console.log(`${list.join(",")}.`)
}
let x; 
test('a','b','c')
test('a',null,'c'); // null is a falsy value
test('','','c')
test('a')
test('','b')
test(x); // undefined (falsy)
test(0,0,0); // falsy values

如果我理解你的意图,就应该这样做。

function test(...args) {
const res = args.filter(i => i).join(',')
return res + (res && ".")
}

// Usage
console.log(test('a','','c')); // "a,c."
console.log(test('a','b','c')); // "a,b,c."
console.log(test('','','c')); // "c."
console.log(test('a', '', '')) // "a."
console.log(test('', '', '')) // ""

使用Array.reduce()函数迭代参数列表中的每个参数,并添加逗号分隔符,然后返回最终字符串。

function test(...args){
return args.reduce((prev, current, index) => {
if (current.length !== 0) {
const separator = prev.length === 0 ? "" : ",";
prev += `${separator}${current}` 
}
if (index === args.length - 1) {
prev += ".";
}
return prev;
}, "");
}
console.log(test('a','','c'));

使用数组联接方法,我们可以将所有输入添加到数组中。然后过滤掉空条目并用逗号分隔符连接。

function test(a,b,c) {
var array = [a, b, c];
return array.filter(x => x).join(", ") + ".";
}
console.log(test('a','','c'));

实际上,函数的一个更好的函数签名应该接受一个数组,它允许使用任意数量项的分隔符进行concat。

最新更新