[英]JavaScript: How to get two elements in a array to equal any given number
My question is:我的问题是:
If I have a array like this, example:如果我有这样的数组,例如:
var myArray = [1,2,4,6,9]
and I want to get the number 15 by getting (adding) the index of 6 and 9.我想通过获取(添加)6 和 9 的索引来获得数字 15。
How do I do that?我怎么做?
I can't make it work and I have tried endlessly... please help.我无法让它工作,我已经无休止地尝试过......请帮忙。
My attempt:我的尝试:
var list = [1,3,5,7,9];
function sumOfIndex(list , weight) {
weight = [];
for (i = 0; i < list.length; i++) {
for (j = 0; j < list[i].length; j++) {
list.push(weight);
}
}
}
In the array from your example, the index of 6 is [3]
and the index of 9 is [4]
.在您的示例中的数组中, 6 的索引是
[3]
, 9 的索引是[4]
。
Simply add them together and you have 15.只需将它们加在一起,您就有 15 个。
Run the snippet below:运行下面的代码片段:
var myArray = [1,2,4,6,9] console.log(myArray[3] + myArray[4])
I'd go over the array and create a map from the complement of each element to its index:我会遍历数组并创建一个从每个元素的补充到其索引的映射:
function findSum (arr, sum) {
const diffs = new Map();
for (let i = 0; i < arr.length; ++i) {
if (diffs.has(arr[i])) {
return [diffs.get(arr[i]), i];
}
diffs.set(sum - arr[i], i);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.