我可以将String Join函数与其他功能一起使用吗

时间:2020-09-15 05:22:21

标签: javascript string typescript join

let sendData = '';
sendData = `${sendData}email=${currentUser.email}`;
sendData = `${sendData}&first_name=${first_name}`;
sendData = `${sendData}&last_name=${last_name}`;
sendData = `${sendData}&nationality=${nationality}`;
sendData = `${sendData}&date_of_birth=${date_of_birth}`;
sendData = `${sendData}&gender=${gender}`;
sendData = `${sendData}&id_type=${id_type}`;
sendData = `${sendData}&photoid_res=${photoid_res}`;
sendData = `${sendData}&selfie_res=${selfie_res}`;
sendData = `${sendData}&kyc_level=L1`;

我正在尝试通过使用Join func来缩短这段代码!您能给我一些办法来缩短该功能吗?

1 个答案:

答案 0 :(得分:0)

只需将所有内容放入数组中,然后将它们加入即可:

let sendDataArray = [
    `email=${currentUser.email}`,
    `first_name=${first_name}`,
    `last_name=${last_name}`,
    `nationality=${nationality}`,
    `date_of_birth=${date_of_birth}`,
    `gender=${gender}`,
    `id_type=${id_type}`,
    `photoid_res=${photoid_res}`,
    `selfie_res=${selfie_res}`,
    `kyc_level=L1`
];

let sendData = sendDataArray.join('&');

为清楚起见,我在上面的示例中使用了一个单独的变量。但是一旦您了解了代码,就可以在一个表达式中完成它:

let sendData = [
    `email=${currentUser.email}`,
    `first_name=${first_name}`,
    `last_name=${last_name}`,
    `nationality=${nationality}`,
    `date_of_birth=${date_of_birth}`,
    `gender=${gender}`,
    `id_type=${id_type}`,
    `photoid_res=${photoid_res}`,
    `selfie_res=${selfie_res}`,
    `kyc_level=L1`
].join('&');