【问题标题】:Why does this code return a number instead of an array with the array.push()? [duplicate]为什么这段代码使用 array.push() 返回一个数字而不是一个数组? [复制]
【发布时间】:2021-07-14 19:53:44
【问题描述】:

我被要求编写一个将元素添加到数组末尾的函数。但是,如果添加的元素与数组中的元素之一具有相同的值,则不应将该元素添加到数组中。像 add([1,2],2) 应该只返回 [1,2]

我的代码是:

  function add (arr, elem){ 

      if (arr.indexOf(elem) != -1){
           return arr;
      }

      else {

           let newArr = arr.push(elem); 
           return newArr; 
      }

  }

  console.log(add([1,2],3)); // here returns a number '3' instead of an array[1,2,3]

谁能解释为什么我在 else 中得到一个数字而不是数组 'newArr'?

【问题讨论】:

  • 因为根据docspush返回数组的新长度
  • array.push() 返回数组的长度。如果你想要整个数组,只需让你的函数返回arr,不要费心设置newArr

标签: javascript arrays return-value array-push


【解决方案1】:

Array.push 不返回整个数组而是返回新数组的计数

例如:

const colors = ['red', 'blue', 'yellow'];
const count = colors.push('green');
console.log(count); // expected output: 4
console.log(colors); // expected output: Array ["red", "blue", "yellow", "green"]
  • 由于在您的情况下返回 colors.push('green'),因此您在数组推送操作后获得新数组中的元素数。

【讨论】:

    【解决方案2】:

    如果您希望它显示您现有的值,您仍然必须返回 arr

    function add (arr, elem){ 
          if (arr.indexOf(elem) != -1){
               return arr;
          }
          arr.push(elem); 
          return arr;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      相关资源
      最近更新 更多