【问题标题】:Why isn't my nullish coalescing operator (??) working as intended?为什么我的无效合并运算符 (??) 没有按预期工作?
【发布时间】:2022-12-31 19:49:27
【问题描述】:

以下是我的代码的相关部分:

HTML(摘抄)

<label for="name">File delimiter (optional, max 1 character):</label>

<input type="text" id="delimiter" name="delimiter" required
minlength="0" maxlength="1" size="1"><br>

JS(摘抄)

async function getRelease(idFiltered) {
  return fetch(`https://api.***.com/releases/${idFiltered}`, {
    headers: {
      'User-Agent': '***/0.1',
      'Authorization': `*** key=${KEY}, secret=${SECRET}`,
    },
  }).then(response => response.json())
    .then(data => {
      if (data.message === 'Release not found.') {
        return { error: `Release with ID ${idFiltered} does not exist` };
      } else {
        const { country = 'Unknown', genres = [], styles = [], year = 'Unknown' } = data;
        const artists = data.artists?.map?.(artist => artist.name);
        const barcode = data.identifiers.filter(id => id.type === 'Barcode').map(barcode => barcode.value);
        const catno = data.labels.map(catno => catno.catno);
        const descriptions = data.formats.map(descriptions => descriptions.descriptions);
        const format = data.formats.map(format => format.name);
        const labels = data.labels.map(label => label.name);
        const qty = data.formats.map(format => format.qty);
        const tracklist = data.tracklist.map(track => track.title);
        const formattedLabels = labels.map(label => label.name);
        const delimiter = document.getElementById("delimiter").value ?? "|";
        const formattedBarcode = barcode.join(delimiter);
        const formattedCatNo = catno.join(delimiter);
        const formattedGenres = genres.join(delimiter);
        const formattedStyles = styles.join(delimiter);
        const formattedTracklist = tracklist.join(delimiter);
        const preformattedDescriptions = descriptions.toString()
          .replace('"', '""').replace(/,/g, ', ');
        const formattedDescriptions = '"' + preformattedDescriptions + '"';
        console.log(data);

        return [idFiltered,
          artists,
          format,
          qty,
          formattedDescriptions,
          formattedLabels,
          formattedCatNo,
          country,
          year,
          formattedGenres,
          formattedStyles,
          formattedBarcode,
          formattedTracklist
        ];
      }
    });
}

当我在 HTML 页面的文本框中手动输入分隔符 | 时,我得到了正确的输出,例如...

5,Datacide,CD,1,"Album, Limited Edition",,,RI 026|RI026,Germany,1995,Electronic,Abstract|Ambient|Downtempo,,Flashback Signal|Flowerhead|Deep Chair|So Much Light|Sixties Out Of Tune

当我不这样做时,它就不见了!

 5,Datacide,CD,1,"Album, Limited Edition",,,RI 026RI026,Germany,1995,Electronic,AbstractAmbientDowntempo,,Flashback SignalFlowerheadDeep ChairSo Much LightSixties Out Of Tune

我想由于某种原因,缺少的定界符既不评估为null也不评估undefined,因为我读到无效合并运算符仅返回第二个操作数“当第一个操作数评估为nullundefined时(但没有其他虚假值)”source。所以这似乎有效:

    const delimiter = document.getElementById("delimiter").value || "|";

谁能告诉我为什么 ?? 对我不起作用,可以改用 || 吗?谢谢。

【问题讨论】:

  • 我希望 document.getElementById("delimiter").value 返回一个空字符串,它既不是 null 也不是 undefined (但确实为逻辑比较评估为虚假值) - 因此 ?? 运算符不会评估右侧

标签: javascript rest


【解决方案1】:

您的定界符可以是一个空字符串,它是虚假的,但不是无效的。这就是逻辑 or 起作用的原因。空字符串是逻辑假,undefined 和 null 也是如此。 || 运算符将在比?? 运算符更多的情况下返回右边的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 2019-08-28
    • 2014-10-18
    相关资源
    最近更新 更多