This question already has answers here:
Set a default parameter value for a JavaScript function
                                
                                    (26个答案)
                                
                        
                                在4个月前关闭。
            
                    
获取x的默认值:

let defaultX = 3;
function vec1({ x }) {
  x = x || defaultX;
  return { x };
}


用法失败:

vec1({ x: 0 }); // returns { x: 3 }, expected: { x: 0 }

最佳答案

您可以将default value用作未定义的属性。



let defaultX = 3;

function vec1({ x = defaultX }) {
    return { x };
}

console.log(vec1({ x: 0 })); // { x: 0 }
console.log(vec1({}));       // { x: 3 }

10-07 12:27