1

可以将此代码简化为单个作业吗?这三个变量是我从前端收到的输入。我正在使用xssNode.js 中的模块。

var clientname = xss(req.body.clientName, {
    whiteList: [],
    stripIgnoreTag: true,
    stripIgnoreTagBody: ['script']
});
var clientnumber = xss(req.body.clientNumber, {
    whiteList: [],
    stripIgnoreTag: true,
    stripIgnoreTagBody: ['script']
});
var clientaddress = xss(req.body.clientAddress, {
    whiteList: [],
    stripIgnoreTag: true,
    stripIgnoreTagBody: ['script']
});
4

1 回答 1

1

解构迭代方法对此很有用:

const xssOptions = {
    whiteList: [],
    stripIgnoreTag: true,
    stripIgnoreTagBody: [
      "script"
    ]
  },
  [
    clientName,
    clientNumber,
    clientAddress
  ] = [
      "clientName",
      "clientNumber",
      "clientAddress"
    ].map((property) => xss(req.body[property], xssOptions));

在整个分配过程中唯一改变的是属性名称 after req.body,因此将其作为参数传递给 Array 的map调用,将每个属性名称映射到它们各自的xss调用。一旦xss调用返回,它们的返回值以相同的顺序存储在一个数组中,然后分解为三个独立的变量。

或者,您可以使用将它们全部组合在一起的对象:

const xssOptions = {
    whiteList: [],
    stripIgnoreTag: true,
    stripIgnoreTagBody: [
      "script"
    ]
  },
  myXSSObjects = Object.fromEntries([
      "clientName",
      "clientNumber",
      "clientAddress"
    ].map((property) => [
      property,
      xss(req.body[property], xssOptions)
    ]));

console.log(myXSSObjects.clientName);

其他注意事项:

  1. 使用const而不是var.
  2. 按照惯例,JavaScript 标识符使用camelCase,而不是alllowercase.
  3. 将用作第二个参数的对象缓存xss在另一个变量中,以实现可重用性和效率。
于 2021-01-07T09:48:02.367 回答