[英]How to find a number which is the result of added which elements in the array(Javascript)?
For example, there is an array arr[1,2,4,8,16,32,64,128]
, each element represents a permission. 例如,有一个数组
arr[1,2,4,8,16,32,64,128]
,每个元素代表一个权限。 This is the number used for permission assignment. 这是用于权限分配的数字。
One number which is definitely the sum of an element or several elements in an array. 一个数字绝对是一个元素或一个数组中几个元素的总和。
For example: 例如:
1 = arr[0]
6 = arr[1]+arr[2]
11 = arr[0]+arr[1]+arr[3]
17 = 1 + 16
171 = 1 +2 +8 +32 +128
How to find this element or several elements coding with js? 如何找到此元素或使用js编码的几个元素?
Thanks for your help. 谢谢你的帮助。
Even though you probably don't really care what's going on here since it very much smells like an assignment of some sort, this is exactly how answerer feels when asker do not provide enough information that helps with answering the question. 即使您可能并不十分在意这里发生的事情,因为它闻起来很像某种作业,但是当问问者没有提供足够的信息来帮助回答问题时,这正是答复者的感受。
const arr = [1, 2, 4, 8, 16, 32, 64, 128] const getElementIndexes = (n) => { return arr.slice().reverse().reduce((accumulator, currentValue) => { if (n >= currentValue) { accumulator.unshift(arr.indexOf(currentValue)) n = n - currentValue } return accumulator }, []) } console.log(getElementIndexes(1)) console.log(getElementIndexes(6)) console.log(getElementIndexes(11)) console.log(getElementIndexes(17)) console.log(getElementIndexes(171))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.