Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Typescript中对数组或函数使用可选链接?_Javascript_Arrays_Typescript_Function - Fatal编程技术网

Javascript 如何在Typescript中对数组或函数使用可选链接?

Javascript 如何在Typescript中对数组或函数使用可选链接?,javascript,arrays,typescript,function,Javascript,Arrays,Typescript,Function,我尝试使用可选的数组链接,而不是对象链接,但不确定如何做到这一点: 下面是我试图做的myArray.filter(x=>x.testKey===myTestKey)?[0] 但是它给出了这样一个错误,因此如何将它与数组或函数一起使用。您需要在?之后放置,以使用可选链接: myArray.filter(x => x.testKey === myTestKey)?.[0] 仅使用?会使编译器认为您正在尝试使用条件运算符(然后它会抛出一个错误,因为它在后面没有看到:) 可选链接不仅仅是一个打

我尝试使用可选的数组链接,而不是对象链接,但不确定如何做到这一点:

下面是我试图做的
myArray.filter(x=>x.testKey===myTestKey)?[0]


但是它给出了这样一个错误,因此如何将它与数组或函数一起使用。

您需要在
之后放置
,以使用可选链接:

myArray.filter(x => x.testKey === myTestKey)?.[0]

仅使用
会使编译器认为您正在尝试使用条件运算符(然后它会抛出一个错误,因为它在后面没有看到

可选链接不仅仅是一个打字脚本,它也是一个完整的建议

它可以与上述括号符号一起使用,但也可以与点符号属性访问一起使用:

const obj={
提案2:{
嵌套2:‘val2’
}
};
console.log(
对象属性1?嵌套1,
对象prop2?嵌套2

);在上的“最新信息”页面上搜索了一下后才找到它

使用数组的正确方法是在
之后添加

那就好像

myArray.filter(x => x.testKey === myTestKey)?.[0]
我想进一步说明我的上述问题案例到底发生了什么

myArray.filter(x => x.testKey === myTestKey)?[0]
将文件传输到

const result = myArray.filter(x => x.testKey === myTestKey) ? [0] : ;
因此,它会抛出错误,因为后面缺少一些内容:并且您可能不希望您的代码被传输到此文件


多亏了某些性能方面的回答,我学到了有关typescript的新知识,尤其是这个工具。

好吧,尽管我们找到了正确的语法,但代码对我来说没有多大意义

上面代码中的可选链接确保
myArray.filter(x=>x.testKey==myTestKey)
的结果不是
null
,也不是
undefined
(您可以查看TS输出)。但是无论如何这是不可能的,因为
过滤器
方法的结果总是
数组
。由于JavaScript不会抛出“超出数组边界”,因此当您尝试访问任何索引时都是安全的-如果该元素不存在,您将得到
未定义的

更多的例子可以说明这一点:

const myArray: string[] = undefined
console.log(myArray.filter(x => x)?.[0]) //throws Cannot read property 'filter' of undefined
我在Edge Chromium 84上测试的ECMA 262(2020)可以在不使用TypeScript transpiler的情况下执行运算符:

// All result are undefined
const a = {};

console.log(a?.b);
console.log(a?.["b-foo-1"]);
console.log(a?.b?.());

// Note that the following statements throw exceptions:
a?.(); // TypeError: a is not a function
a?.b(); // TypeError: a?.b is not a function

你有什么输入数据,你想要什么结果?这是一个一般性问题,不应该依赖于输入和输出
执行空检查以防止长时间使用
&&
&&
链。这个问题有一个一般性标题,但描述的问题非常具体。除此之外,您还解释了示例中不需要的可选链接。我觉得这一点都不好笑。我觉得你的做法很好笑,如果你投赞成票的话。我认为这是为了达到目的。你有任何建议,我很乐意接受改变。这对Javascript也有效(我认为从2020年起)。类似地,如果函数不是
null
undefined
,则要调用该函数,还可以使用
foo?()
// All result are undefined
const a = {};

console.log(a?.b);
console.log(a?.["b-foo-1"]);
console.log(a?.b?.());

// Note that the following statements throw exceptions:
a?.(); // TypeError: a is not a function
a?.b(); // TypeError: a?.b is not a function