【问题标题】:Javascript: Why .map method returns undefinedJavascript:为什么 .map 方法返回未定义
【发布时间】:2021-12-10 05:22:58
【问题描述】:

我正在使用 .map 方法在 leetcode 中处理这个 problem,但不知何故它返回未定义。有人可以解释为什么会这样吗?我阅读了文档,它说 .map 通常返回一个数组。

var twoSum = function (nums, target) {
    for (let i = 0; i < nums.length; i++){
        const num = nums[i];
        nums.slice(i+1).map((element) => {
            if (num + element === target){
                return [i, nums.indexOf(element, i+1)];
            }
        });
    }
}

【问题讨论】:

  • 因为如果num + element不是=== target,你永远不会在回调中发出return,所以回调隐式返回undefined
  • twoSum 也不会返回任何内容(唯一的return 是从map 回调返回,而不是twoSum)。另外,如果你不使用它产生的数组,你永远不应该使用map(详细信息在我的博客文章here)。

标签: javascript arrays scope


【解决方案1】:

只是添加,这就像一个入门示例,我们可以使用两个指针模式。

应用两个指针的第一个设置是对数组进行排序。

然后取两个指针 第一个从 0 索引开始 第二个从最后一个索引开始

遍历循环并检查目标并相应地增加和减少指针

var twoSum = function(nums, target) {

  nums.sort((a,b) => a-b )
  
  var startingIndex = 0
  
  var lastIndex = nums.length-1;
  
   while(startingIndex<lastIndex){
     
     if(nums[startingIndex] + nums[lastIndex] === target){
       console.log(nums[startingIndex], nums[lastIndex])
       startingIndex++;
       lastIndex--;
     }
     
     if(nums[startingIndex] + nums[lastIndex] < target){
       startingIndex++;
     }
     
     if(nums[startingIndex] + nums[lastIndex] > target){
       lastIndex--;
     }
   }
  
  
};

console.log(twoSum([2, 7, 20, 13, 15], 33));

【讨论】:

    【解决方案2】:

    您可以在这里使用Map 来高效地实现结果

    var twoSum = function(nums, target) {
      const map = new Map();
      for (let i = 0; i < nums.length; ++i) {
        if (map.has(nums[i])) return [map.get(nums[i]), i];
        else map.set(target - nums[i], i);
      }
    };
    
    console.log(twoSum([2, 7, 11, 15], 9));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多