我嘗試使用此表達式來執行此操作。如何通過lodash一行生成1-10 3次
_.times(3, _.random(1, 10))
但返回此:
[undefined, undefined, undefined]
我希望得到這樣的:
[3, 7, 5]
我嘗試使用此表達式來執行此操作。如何通過lodash一行生成1-10 3次
_.times(3, _.random(1, 10))
但返回此:
[undefined, undefined, undefined]
我希望得到這樣的:
[3, 7, 5]
您可以在回調中包裝隨機呼叫,因爲_.times
需要迭代器。這是你的情況,結果爲undefined
。
console.log(_.random(1, 10)); // number, not a function
console.log(_.times(3, 42)); // call with a number
console.log(_.times(3, i => _.random(1, 10))); // call with function
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
這裏是一個快速的方法來做到這一點的3個值 -
var nums[3];
for(var x = 0;x<3;x++){num[x] = random(1,10);}
_.map(new Array(3),() => _.random(1,10))
這工作,因爲數組構造認爲一個整數作爲arrayLength唯一的參數。
因爲我們現在有一個長度爲3的數組,所以我們可以使用map
來返回一個長度相同的新數組,但每個值都是從函數的返回值中生成的。
通常最好是解釋一個解決方案,而不是隻發佈一些匿名代碼行。你可以閱讀[我如何寫一個好的答案](https://stackoverflow.com/help/how-to-answer),還有[完全解釋基於代碼的答案](https://meta.stackexchange.com /問題/ 114762 /解釋-entirely-%E2%80%8C%E2%80%8Bcode基於-答案)。 –
@MassimilianoKraus更新以添加解釋 –