Swift对应的JavaScript是什么?操作符

What is the JavaScript equivalent for Swift ?? operator

本文关键字:是什么 操作符 JavaScript Swift      更新时间:2023-09-26

在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.

如果您想从falsey值中排除0,那么

x = ( ( y === 0 || y ) ? y : z ); //x is y unless y is null, undefined, "", '', or 0.

或者如果您想将false也从falsey值中排除,则

x = ((y === 0 || y === false || y) ? y : z);

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);
}

三元运算符将获得类似的结果

x = (y ? y : z)

严格来说,为了避免隐式类型转换,您可能需要像

这样的内容
x = (null !== y ? y : z)

x = x || y这样的短路赋值感觉像是对||操作符的误用,可能会导致以后的混乱。但是,我认为用什么是个人喜好的问题。