如果在JavaScript中为null或未定义,则替换值

Val*_*yev 107 javascript

我有一个要求将??C#运算符应用于JavaScript,我不知道如何.在C#中考虑这个:

int i?=null;
int j=i ?? 10;//j is now 10
Run Code Online (Sandbox Code Playgroud)

现在我在JavaScript中设置了这个:

var options={
       filters:{
          firstName:'abc'
       } 
    };
var filter=options.filters[0]||'';//should get 'abc' here, it doesn't happen
var filter2=options.filters[1]||'';//should get empty string here, because there is only one filter
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

谢谢.

编辑:我发现了一半的问题:我不能使用'indexer'表示对象(my_object[0]).有没有办法绕过它?(我事先不知道过滤器属性的名称,也不想迭代它们).

Gum*_*mbo 244

这是JavaScript的等价物:

var i = null;
var j = i || 10; //j is now 10
Run Code Online (Sandbox Code Playgroud)

请注意,逻辑运算符||不返回布尔值,而是返回可转换为true的第一个值.

另外使用一个对象数组而不是一个对象:

var options = {
    filters: [
        {
            name: 'firstName',
            value: 'abc'
        }
    ]
};
var filter  = options.filters[0] || '';  // is {name:'firstName', value:'abc'}
var filter2 = options.filters[1] || '';  // is ''
Run Code Online (Sandbox Code Playgroud)

这可以通过索引访问.

  • 请注意,如果0是i的有效值,则不起作用. (48认同)
  • 如果任何falsey是一个潜在有效的输入(`0`,`false`,空字符串),我会做这样的事情:`var j =(i === null)?10:i;`哪个只会替换`null`,而不是任何可以被评估为false的东西. (12认同)
  • @phil294 `var j = (i != null ? i : 10);` 应该可以工作,因为 `undefined` 是 `==` null,所以 `i != null` 对于 `null` 和 `未定义`。 (2认同)

wen*_*jun 20

ES2020 答案

新的Nullish Coalescing Operator 终于在 JavaScript 上可用了。但是,请注意浏览器支持。您可能需要使用像Babel这样的 JavaScript 编译器将其转换为更向后兼容的内容。

根据文档,

空合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为空或未定义时返回其右侧操作数,否则返回其左侧操作数。

const options={
  filters:{
    firstName:'abc'
  } 
};
const filter = options.filters[0] ?? '';
const filter2 = options.filters[1] ?? '';
Run Code Online (Sandbox Code Playgroud)

这将确保您的两个变量都有一个后备值''iffilters[0]filters[1]are null, or undefined

请注意,nullish 合并运算符不会返回其他类型的假值(例如0and )的默认值''。如果您希望考虑所有虚假值,您应该使用 OR 运算符||


Gib*_*olt 13

逻辑空赋值,2020+ 解决方案

添加了一个新的运算符,??=。这相当于value = value ?? defaultValue.

||=并且&&=是相似的,下面的链接。

这将检查左侧是否未定义或为空,如果已定义则短路。如果不是,则左侧被分配右侧值。

基本示例

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

// Equivalent to
a = a ?? true
Run Code Online (Sandbox Code Playgroud)

对象/数组示例

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }
Run Code Online (Sandbox Code Playgroud)

功能示例

function config(options) {
    options.duration ??= 100
    options.speed ??= 25
    return options
}

config({ duration: 555 })   // { duration: 555, speed: 25 }
config({})                  // { duration: 100, speed: 25 }
config({ duration: null })  // { duration: 100, speed: 25 }
Run Code Online (Sandbox Code Playgroud)

??= 浏览器支持2021 年 7 月 - 85%

??= Mozilla 文档

||= Mozilla 文档

&&= Mozilla 文档


Mar*_* An 9

总而言之:

int j=i ?? 10;在 javascript 中使用也非常好。只需替换intlet.

??||

??应该首选,||因为它仅检查 null 和 undefined

以下所有表达式均正确:

(null || 'x') === 'x' ;
(undefined || 'x') === 'x' ;
//Most of the times you don't want the result below
('' || 'x') === 'x'  ;
(0 || 'x') === 'x' ;
(false || 'x') === 'x' ;
//-----

//Using ?? is preferred
(null ?? 'x') === 'x' ;
(undefined ?? 'x') === 'x' ;
//?? works only for null and undefined, which is in general safer
('' ?? 'x') === '' ;
(0 ?? 'x') === 0 ;
(false ?? 'x') === false ;

Run Code Online (Sandbox Code Playgroud)

Asterisk:检查浏览器兼容性,如果您确实需要支持这些其他浏览器,请使用babel


Ale*_*ski 6

我发现了一半问题:我不能对对象使用'indexer'表示法(my_object [0]).有没有办法绕过它?

没有; 顾名思义,对象文字是一个对象,而不是一个数组,因此您不能简单地根据索引检索属性,因为它们的属性没有特定的顺序.检索其值的唯一方法是使用特定名称:

var someVar = options.filters.firstName; //Returns 'abc'
Run Code Online (Sandbox Code Playgroud)

或者使用for ... in循环迭代它们:

for(var p in options.filters) {
    var someVar = options.filters[p]; //Returns the property being iterated
}
Run Code Online (Sandbox Code Playgroud)