xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js optional chaining operator

js optional chaining operator

js 可选链

可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。
?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。
与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

console.log(adventurer.someNonExistentMethod?.());
// undefined

console.log(adventurer.cat?.name);
// undefined

console.log(adventurer.dog?.name);
// undefined

console.log(adventurer.dog.name);
// Error: Cannot read property 'name' of undefined



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

demo

foo = {};
{}
foo.level1 = {};
{}
foo;
{level1: {…}}
foo.level1.level2 = {};
{}
foo.level1.level2.bar = 1;
1


const checkNested = (obj, level,  ...rest) => {
  if (obj === undefined) {
     return false;
  }
  
  if (rest.length === 0 && obj.hasOwnProperty(level)) {
    return true;
  }  
  return checkNested(obj[level], ...rest)
}

foo?.level1?.level2?.level3;
undefined
foo?.level1?.level2?.bar;
1
foo?.level1?.level2?.baz;
undefined
foo?.level1?.level2;
{bar: 1}

https://medium.com/javascript-in-plain-english/javascript-tips-listeners-sorting-and-nested-objects-a81a9755fe65

refs



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2021-01-22 23:54  xgqfrms  阅读(130)  评论(1编辑  收藏  举报