JS中return语句中的问号是什么意思?

Yar*_*tur 5 javascript function reactjs

我有一个函数服务于来自加载程序的使用数据,并以正确的方式为我转换它,然后返回新数据我有一个使用“?”的建议。如果没有来自加载程序的数据,则在转换中返回数据之前可能会有意义:


export default async function serviceInputSearch(url) {
  const data = await new DataLoader(url).get();
  return data?.data.results;
}

Run Code Online (Sandbox Code Playgroud)

我在谷歌中找不到关于这个“?”的任何信息 在退货声明中?这是什么意思?

小智 9

这称为可选链接。您可以在此处找到有关它的更多信息:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

但是,鉴于您的示例,其要点是问号验证是否存在有效的“数据”对象。如果那里没有问号,也没有数据对象或为空,则在“无法读取'未定义'的属性数据”行中会抛出错误。


K.T*_*ess 5

这称为可选链

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

// you can use it to check if the property is exist in the object
const dogName = adventurer.dog?.name; //same as adventurer.dog && adventurer.dog.name ? adventurer.dog.name : undefined;
console.log(dogName); //undefined
Run Code Online (Sandbox Code Playgroud)

否则你可以用它来检查/调用对象内部函数的存在

// if someNonExistentMethod is exists in the adventurer Object call it.
console.log(adventurer.someNonExistentMethod?.());
Run Code Online (Sandbox Code Playgroud)

语法是

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  },
  skills: ['jump']
};

obj.val?.prop => //Optional chaining
    ex: adventurer.dog?.name

obj.val?.[expr] => //Optional chaining with expressions
    ex: const propertyName = 'name'; adventurer.dog?.[propertyName];

obj.arr?.[index] => //Array item access with optional chaining
    ex: adventurer.skills?.[0] //jump

obj.func?.(args) => //Optional chaining with function calls
    ex: adventurer.someNonExistentMethod?.()
Run Code Online (Sandbox Code Playgroud)


Ifa*_*uki 5

它是“可选链接”运算符。

这是一个用例:

let obj = {};

console.log(obj?.person?.age);
console.log(obj.person.age);
Run Code Online (Sandbox Code Playgroud)

如果您尝试访问不存在的属性,它会很方便。所以undefined你会得到错误cannot get xx of undefined

为了防止这个错误,你?.在它前面放了一个,它会返回一个undefinedback 而不是抛出错误

这里有一些例子:

let obj = {};


//method does not exist
console.log(obj.func?.())


let arr = ["tom"];
console.log(arr[2]?.name);


let matrix = [ [ 1 ], [ 2 ] ];
console.log(matrix[5]?.[3]);


let defaultName = obj?.name ?? "Tom";
console.log(defaultName);
Run Code Online (Sandbox Code Playgroud)