在swift中,x = y ?? z意味着x等于y,除非y为null/nil,在这种情况下,x等于z.什么是JavaScript等价物?
x = y || z; //x is y unless y is null, undefined, "", '', or 0.
Run Code Online (Sandbox Code Playgroud)
如果0要从falsey值中排除,
x = ( ( y === 0 || y ) ? y : z ); //x is y unless y is null, undefined, "", '', or 0.
Run Code Online (Sandbox Code Playgroud)
或者如果你想false从falsey值中排除那么,
x = ((y === 0 || y === false || y) ? y : z);
Run Code Online (Sandbox Code Playgroud)
DEMO
var testCases = [
[0, 2],
[false, 2],
[null, 2],
[undefined, 2],
["", 2],
['', 2],
]
for (var counter = 0; counter < testCases.length - 1; counter++) {
var y = testCases[counter][0],
z = testCases[counter][1],
x = ((y === 0 || y === false || y) ? y : z);
console.log("when y = " + y + " \t and z = " + z + " \t then x is " + x);
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |