是否有带有可选链/空合并的糖来防止Array.map出现Typeerrors?

 收藏

Is there any sugar to ensure that map will not typeerror using tools like optional chaining/nullishcoalescing?

let x = {y: 1, z: 2};

x?.map(i => i); // Typeerror
Array.isArray(x)?.map(i => i); // Typeerror

let y = '1234';
y?.length && y.map(i => i) // Typeerror
回复
  • ueos 回复

    这些类型错误似乎是正确的。您显然不能在对象文字,布尔值或字符串上调用map。

    If you want to optionally call map anyways, you can continue the optional chaining with ?.(params):

    
    let x = {y: 1, z: 2};
    
    x?.map?.(i => i);
    Array.isArray(x)?.map?.(i => i);
    
    let y = '1234';
    y?.length && y.map?.(i => i)