为什么此代码 return 是一个数字而不是带有 array.push() 的数组?

Why does this code return a number instead of an array with the array.push()?

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

我的代码是:

  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'?

如果您想让它显示您现有的值,您仍然需要 return arr

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

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

例如:

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"]
  • 因为你return colors.push('green') 在你的情况下,你在数组推送操作后得到新数组中元素的数量。