2017-09-01 52 views
1

在Lodash,有沒有辦法做這樣的事情:使第一個「truthy」值分配給foo在Lodash(JavaScript)中,是否有返回第一個「真值」或「有意義」值的函數?

foo = firstTruthy(foo, bar, 10); 

?引用「truthy」是因爲某些值,如0""想要被認爲是真的。


背景信息:在JavaScript中,如果我們做

foo = foo || 10; 

因此,如果foo是不確定的,那麼它被設置爲0,但後來有一個陷阱:如果foo0,它也被視爲falsy,因此foo被賦值爲10.在Lodash或通用JavaScript中,是否有辦法執行類似

foo = firstTruthy(foo, 10);   // this 
foo = firstTruthy(foo, bar, 10); // or this 

,以便第一個真值被分配到foo,其中truthy被認爲是:所有不是false,nullundefined? (所以即使0""被認爲是truthy,類似於Ruby)。

回答

3

如果你不想要a = b || c,那麼你濫用術語「真理」。 「Truthy」值的定義很明確,您不能隨意在該定義中包含其他值,如0""

如果你想編寫自己的「分配要麼是truthy或零或條件的一些其他組合的價值」,用Array#find

var value = [foo, bar, baz].find(x => x || x == 0 || x == ""); 
0

你可以做這樣的事情:

function firstTruthy(...args) { 
    return args.find(arg => arg !== null && arg !== undefined && arg !== false); 
} 
0

你可以檢查值的真實性或與Array#includes檢查。

const firstTruthy = (...array) => array.find(a => a || [0, ''].includes(a)); 
 

 
console.log(firstTruthy(undefined, null, 10)); // 10 
 
console.log(firstTruthy(undefined, 0, 10)); // 0 
 
console.log(firstTruthy(false, '', 10));  // ''

0

時沒有談到JavaScript的非常具體的是什麼 「truthy」 的定義,不要使用 「truthy」。 你所要求的是我用來指代的東西 vs 沒有什麼。 AFAIK Lodash沒有這樣的功能。這是我去到解決方案,這:

/** 
* Return the first provided value that is something, or undefined if no value is something. 
* undefined, null and NaN are not something 
* All truthy values + false, 0 and "" are something 
* @param {*} values Values in order of priority 
* @returns {*} The first value that is something, undefined if no value is something 
*/ 
function getSomething(...values) { 
    return values.find(val => val !== null && val !== undefined && !Number.isNaN(val)); 
} 

從這裏你問什麼不同的是,我的函數考慮false東西。這很容易進行調整。

+0

是,「某事」或「有意義」......如果某人的銀行賬戶有$ 1美元,那麼這是真的,那麼$ 0不應該是虛假的,因爲它是有效的賬戶價值。同樣對於字符串搜索,如果在位置0找到搜索關鍵字,那麼它也被找到,與1或20相同。 –

相關問題