Javascript:如何向模板文字添加可选的正斜杠

Javascript: How to add an optional forward slash to a template literal

所以我试图有两个可选参数和一个可选的正斜杠。我需要一个可选的正斜杠的原因是因为基础 url 只是 localhost:3000/web/reserve 而不是 localhost:3000/web/reserve/。当没有将任何内容传递给 webpageCheck 时,默认的空参数按预期工作,但是我无法使可选的 (/) 工作。如果我这样做 http://localhost:3000/web/reserve/${label}${count} 它会在调用 webpageCheck 时失败,因为末尾没有正斜杠。有人知道怎么做吗?

const web = {
        label: 'Hello',
        count: '10',
    };
    
const webpageCheck = (label = '', count = '') => {
     const optionalSlash = '/'
      cy.url().should(
         'eq',
         `http://localhost:3000/web/reserve${optionalSlash + label}${optionalSlash + count}`
        );
    };
    
 webpageCheck()

您可以将零件收集在一个数组中,通过布尔值过滤并加入所需的分隔符。

const
    web = { label: 'Hello', count: '10' },
    webpageCheck = (label = '', count = '', separator = '/') => 
        ['http://localhost:3000/web/reserve', label, count]
            .filter(Boolean)
            .join(separator);

console.log(webpageCheck());
console.log(webpageCheck(web.label));
console.log(webpageCheck(web.label, web.count));

所以,听起来 optionalSlash 应该在 labelcount 之前的字符串中,如果缺少 labelcount,我们跳过为该变量添加 optionalSlash 。如果是这样,您可以在构造字符串时执行 simple ternary

`http://localhost:3000/web/reserve${
  label ? optionalSlash + label : ''
  }${
  count ? optionalSlash + count : ''}`

你应该尝试用你的逻辑定义一个字符串,像这样:

const web = {
        label: 'Hello',
        count: '10',
    };
    
const webpageCheck = (label = '', count = '') => {
     //Logic example
     let addressOptionsString=(label!==''? ("/" + label):'') + (count!==''? ("/" + count):'')
      cy.url().should(
         'eq',
         `http://localhost:3000/web/reserve${adressOptionsString}`
        );
    };
    
 webpageCheck()

您可以匿名处理参数,允许任意数量的路径段

const webpageCheck = (...args) => {
  const path = [...args].map(arg => `/${arg}`).join('')
  const expected = `http://localhost:3000/web/reserve${path}`
  cy.url().should('eq', expected)
}

如果 label 解析为 undefined 但存在 count,那应该算作一个错误

const webpageCheck = (...args) => {
  const path = [...args].map(arg => `/${arg}`).join('')
  expect(path).not.to.include('undefined')

  const expected = `http://localhost:3000/web/reserve${path}`
  cy.url().should('eq', expected)
}