我想動態地指定負值,正如在這個確切的問題中看到的那樣。
我還想使用一些動態括號符號的方法來完成這個任務,使用相當于負數余數的字串(模子操作)。
bucketObj[key]報告未定義,因為我沒有預先設定一個鍵來存盤一個相應的值。 我如何以括號符號、點符號或兩者的形式動態地設定物件的鍵呢?
。 function toDigitBuckets(array, radix) {
let bucket = JSON.parse(JSON。 stringify([...Array(radix).fill([]) ])。
let bucketObj = Object.assign(bucket)。
array.forEach(span class="hljs-params">val => { let key = String。 toString(val % 10); bucketObj[key].push(val) })。)
return bucket。
}
let array = [-7, -49, 84, 39, -31, 95, 7, -8, -13, -32, 93, 40, -81, -30, -57, -57, 49, 66, -64, 42, 35, 29, -57, 41, 93, 34, -45, -15, 51, 16, 97, -88, 52, -69, 56, -16, -91, 51, 10, -21, 80, 78, -5, 18, -20, -98, 72, -94, 11, -83, -31, 13, -21, 39, -47, 8, -98, 95, 52, -18, 77, -11, -38, -46, -98, 48, -45, -4, 76, -32, -81, 67, -82, 9, -60, -20, 0, 33, -12, 77, 65, 45, -22, 99, -47, -83, -81, 10, -99, 16, 23, 5, -57, 89, -62, 9, -16, 79, 5, -2】。]
let radix = 10;
console.log(JSON. stringify(toDigitBuckets(array, radix));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你可以使用Array#reduce,用一個物件作為累積器。
function toDigitBuckets(array, radix) {
return array.reduce((acc, curr) =>
((acc[curr % radix] ??= []).push(curr), acc), {})。
}
let array = [-7, -49, 84, 39, -31, 95, 7, -8, -13, -32, 93, 40, -81, -30, -57, -57, 49, 66, -64, 42, 35, 29, -57, 41, 93, 34, -45, -15, 51, 16, 97, -88, 52, -69, 56, -16, -91, 51, 10, -21, 80, 78, -5, 18, -20, -98, 72, -94, 11, -83, -31, 13, -21, 39, -47, 8, -98, 95, 52, -18, 77, -11, -38, -46, -98, 48, -45, -4, 76, -32, -81, 67, -82, 9, -60, -20, 0, 33, -12, 77, 65, 45, -22, 99, -47, -83, -81, 10, -99, 16, 23, 5, -57, 89, -62, 9, -16, 79, 5, -2】。]
let radix = 10;
console.log(toDigitBuckets(array, radix));
. as-console-wrapper{max-height:100%! important; top:0}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/322448.html
標籤:
