[英]How to filter only values with type Symbol in an array?
I'm working on arrow library where I'm creating a function that returns only elements with type Symbol
.我正在研究箭头库,我正在创建一个函数,该函数仅返回类型为
Symbol
元素。
I use the filter
function on an array :我在数组上使用
filter
函数:
export const extractSymbol = array => {
if (isArray(array)) {
return array.filter(value => typeof value === "symbol")
}
}
But because I'm creating tests before the implementation, This test fail :但是因为我在实现之前创建了测试,这个测试失败了:
expect(extractSymbol([1, 2, 4, Symbol('vue'), Symbol('react')])).toStrictEqual([Symbol('vue'), Symbol('react')]);
I expected true but it returns :我期望为真,但它返回:
Expected: [Symbol(vue), Symbol(react)]
Received: serializes to the same string
Two symbols created with the same parameter are not equal to each other:使用相同参数创建的两个符号彼此不相等:
console.log( Symbol('foo') === Symbol('foo') );
For the test to work properly, define the symbols outside the expect
, so you can pass the same reference to both arrays:为了使测试正常工作,请在
expect
之外定义符号,以便您可以将相同的引用传递给两个数组:
const s1 = Symbol('vue');
const s2 = Symbol('react');
expect(extractSymbol([1, 2, 4, s1, s2])).toStrictEqual([s1, s2]);
Try this:尝试这个:
let arr = [Symbol('foo'), 123]; let filtered = arr.filter(x => typeof(x) == 'symbol'); console.log(filtered);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.