简体   繁体   English

如何获取链中前一个数组的长度 function

[英]How to get length of previous array in chain function

Try to do something with array with unpredictable result, something like return random member of filtered array尝试对结果不可预测的数组做一些事情,比如返回过滤数组的随机成员

let tempArr = [1,2,3,4,5].filter(x=>x>2);
return tempArr[Math.floor(Math.random()*tempArr.length)];  // 3, 4 or 5

Just want to make it more clear by using chain function, but the following code is not working, this.length is always 1只是想通过使用链 function 使其更清楚,但是以下代码不起作用, this.length始终为1

return [1,2,3,4,5]
         .filter(x=>x>2)
         .at(Math.floor(Math.random()*this.length)); // always returns `3`

What's the correct way to do this?执行此操作的正确方法是什么?

I doubt you can achieve that flow with vanila js, but if you use something like the lodash library, you can make the chain and make code more readable.我怀疑你能否使用 vanila js 实现该流程,但如果你使用类似lodash库的东西,你可以制作链并使代码更具可读性。

 const result = _([1,2,3,4,5]).filter(x => x > 2).sample(); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top: 0 }
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM