我有這個功能:
function(x, callBack) {
const c = x?.properties.color || red
const h = x?.properties.high || 1
const a = x?.properties.alt || 5
const la = x?.properties.lat || 4
const lo = x?.properties.lon || 3
const w = x?.properties.width ||| 2
callBack(c, h, a, la, lo, w)
}
如何使用此運算子減少行數{ color } = x?.properties?我的問題是默認值。
uj5u.com熱心網友回復:
由于所有的值都在里面properties,我們可以使用帶有后備值的擴展語法。
唯一發生的“變化”是您需要使用原始鍵而不是短變數名
function fooBar(x, callBack) {
const {
color = 'red',
high = 1,
alt = 5
} = x?.properties || {};
callBack(color, high, alt);
}
fooBar({ properties: { color: 'orange' } }, (...all) => console.log('#1', all));
fooBar({ properties: undefined }, (...all) => console.log('#2', all));
注意:正如@Felix提到的,請記住邏輯 OR ( ||)除了 fallback 之外還有其他一些行為=。
uj5u.com熱心網友回復:
您可以一直使用物件解構:
function f({properties: {color: c = 'red', high: h = 1, alt: a = 5, lat: la = 4, lon: lo = 3, width: w = 2} = {}} = {}, callBack) {
callBack(c, h, a, la, lo, w);
}
const callbackFunction = function() {
console.log(...arguments);
}
f(undefined, callbackFunction)
f({ properties: {} }, callbackFunction)
f({ properties: { color: 'test', alt: 4 } }, callbackFunction)
或者,如果您不需要重命名所有變數,只需使用
function f({properties: {color = 'red', high = 1, alt = 5, lat = 4, lon = 3, width = 2} = {}} = {}, callBack) {
callBack(color, high, alt, lat, lon, width);
}
我用過= {}兩次(一次將properties屬性的默認值設定為空物件以防它不存在,一次將第一個引數的默認值作為一個整體設定為空物件以防它完全不存在/ undefined)這樣它就不會在這些情況下拋出任何錯誤。這與您的代碼略有不同,如果傳遞了一個物件,但缺少該屬性,它將引發錯誤。properties
另一個小的區別是它將對任何假||值使用右手運算元,而物件解構中的默認值僅在其值為 時使用。undefined
uj5u.com熱心網友回復:
你可以像這樣處理它,但是當你檢查 nullish 運算子時它可能會回傳 undefined,你必須提前處理好。
function (x, callBack) {
const properties = x?.properties || {};
const {
color = 'red',
high = 1,
alt = 5,
lat = 4,
lon = 3,
width = 2
} = properties;
callBack(color, high, alt, lat, lon, width);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/476383.html
標籤:javascript
