2017-09-01 49 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相同。 –

相关问题