javascript中的数组的问题

小明明明明明 2017-08-21 12:54:26
题目是这个:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


我的答案:
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
function twoSum(nums, target) {
nums.forEach(function(num,i) {
var index = nums.indexOf(target - num);
if(index !== -1 && index !== i){
return [index,i];

}
});
}


请问为什么达不到想要的效果呀
...全文
85 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
75闪光雷 2017-08-21
  • 打赏
  • 举报
回复
你为什么不自己写for循环呢?
冬狮郎sun 2017-08-21
  • 打赏
  • 举报
回复
leetcode上面第一题,我的答案

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    for(var i = 0,len = nums.length;i<len;i++){
        for(var j = i+1;j<len;j++){
            if(nums[i]+nums[j] == target){
                return [i,j];
            }
        }
    }
};
Go 旅城通票 2017-08-21
  • 打赏
  • 举报
回复
return是forEach的返回值又不是你函数的
    function twoSum(nums, target) {
        var rst=null////////////
        nums.forEach(function (num, i) {
            var index = nums.indexOf(target - num);
            if (index !== -1 && index !== i) {
                rst= [index, i];//////////

            }
        });
        return rst;///////////
    }


推荐学习资料
javascript解码读取二维码信息
javascript生成二维码
swing wang 2017-08-21
  • 打赏
  • 举报
回复
没怎么看懂题的意思,看看这样行不行

function getResult(integers,target){
  for(var i in integers){
    for(var j =0; j<integers.length;j++){
      if(integers[i]+integers[j]==target){
        retrun [i,j];
      }
    }
  }
}

87,904

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧