简体   繁体   English

如何显示给定数组中两个相同数字的索引

[英]How can I show the index of two same number in a given array

I'm trying to create a function with the parameters (number, target) that returns the index of two numbers in a given array that is equal to sum of the target.我正在尝试使用参数 (number, target) 创建一个 function ,它返回给定数组中两个数字的索引,该索引等于目标的总和。 Here's the code so far:到目前为止,这是代码:

   const twoSum = function (nums, target) {

    let num1;
    let num2;
    let index1;
    let index2;

    for(let i = 0;  i < nums.length; i++){
      
        num1 = nums[i];
        num2 = target - num1;
       
        if(nums.includes(num2){
            index1 = nums.indexOf(num2);
            index2 = nums.indexOf(num1);
        }
    
    }
    return [index1, index2];
}

The problem is;问题是; when the array consists of like numbers, it returns just the index of the first number twice eg twoSum([5,5,3], 10) returns [0,0] instead of [0,1]当数组由相似的数字组成时,它只返回第一个数字的索引两次,例如twoSum([5,5,3], 10)返回[0,0]而不是[0,1]

I don't know exactly what you are looking for, but this will give you what you described.我不知道你在找什么,但这会给你你所描述的。

const twoSum = function (nums, target) {

    let num1;
    let num2;
    let index1;
    let index2;

    for(let i = 0;  i < nums.length; i++) {
      
        num1 = nums[i];
        num2 = target - num1;
       
        if(nums.includes(num2)) {
            index1 = nums.indexOf(num1);
            if(num1 === num2) {
                index2 = nums.findIndex((num, i) => num === num2 && i != index1);
                if(index2 === -1) return -1; //returns -1 if no second number was found
            } else {
                index2 = nums.indexOf(num2); 
            }
            return [index1, index2]; 
        }
    
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获得与 JavaScript 中给出的相同数值? - How can i get the same number value as given in JavaScript? 如何在数组中编号相同的元素? - How I can number of the same elements in array? 如何使用Materializecss在同一个div上显示两个工具提示? - How Can I show two tooltips on the same div with Materializecss? 如何在javaScript中创建一个带有索引和键的二维数组? - How can I create a two dimensional array with index and with key in javaScript? 我需要在 javascript 中创建一个函数来显示有多少个数组成员小于给定的数字 - I need to create a function in javascript to show how many members of array are less than a given number 如何同时在数组中存储和显示数据? - How can I store and show data in array at the same time? 如何将数据元素同时推送到两个数组? - How can i push data elements to two array at same time? 如何将第一个索引号添加到数组中的 n 个索引时间? - How can i add the first index number to n index times in array? 给定JavaScript中的特定索引,如何将元素从一个数组复制到另一种不同类型的数组? - How can I copy elements from one array to another of a different type given a particular index in JavaScript? 如何使用map函数和给定索引为数组元素设置特定位置? - How can I set a specific position to array elements with the map function and a given index?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM