简体   繁体   English

JavaScript:如何使数组中的两个元素等于任何给定数字

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

相关问题 如何在javascript数组中找到相等元素的数量 - How to find the number of equal elements in javascript array 如何计算给定数字以下/上方的数组中的元素数(javascript) - How to count the number of elements in an array below/above a given number (javascript) Javascript 检查数组中是否有任何元素相等 - Javascript check if any elements in array are equal 检查数组中数组中任何元素的和是否等于给定值 - checking an array if sum of any elements in array equal to given value 计算数组中两个元素小于或等于总和的次数-Javascript - Count number of times two elements in array are less than or equal to a sum value - Javascript javascript仅获取等于变量的数组元素 - javascript get only array elements equal to variable 查找数组中有多少项大于等于或小于给定数字 Javascript - Find how many items in array are greater equal or less than given number Javascript 编写一个 JavaScript 程序从数组中的三个给定数字中检查一个数字,其中两个数字相等,找到第三个 - Write a JavaScript program to check a number from three given numbers in an array where two numbers are equal, find the third one 如何在Javascript中获取另一个数组中某个数组元素的数字出现次数? - How to get number occurrences of any element of an array in another array in Javascript? 元素少于或等于给定数组中元素的数组 - Arrays with elements less or equal to the elements in given array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM