简体   繁体   English

如何找到一个数字,该数字是在数组(Javascript)中添加哪些元素的结果?

[英]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.

相关问题 如何在一个数组中查找不在 Javascript 中的另一个数组中的元素? - How to find elements in one array which are not in another array in Javascript? 从一个数组中查找所有元素,当添加时给出 28? - Find all Elements from an array which when added gives 28? 有没有一种方法可以使单击元素数组时在javascript函数内添加的元素仅添加一次? - Is there a way so that elements which are getting added inside javascript function on the click of array of elements should be added only once? 获取使用javascript添加的类的元素 - Get elements with class which was added with javascript 如何在javascript数组中找到相等元素的数量 - How to find the number of equal elements in javascript array 如何在JavaScript中找到数组的数字元素的乘法? - How to find multiplication of the number elements of array in javascript? 如何将单击功能添加到在 javascript 中动态添加的按钮数组? - How to add click function to a array of buttons which is added dynamically in javascript? 如何为在其属性中包含 javascript 的元素找到 XPath? - how to find XPath for elements which consist javascript in it attributes? 如何使用 JavaScript 查找所有具有事件侦听器的元素? - How to use JavaScript to find all elements which have event listeners? 如何通过具有嵌套对象元素的JSON数组查找 - How to find through JSON array which has nested object elements
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM