A good JavaScript to add/remove items from/to array?

前端 未结 4 1838
名媛妹妹
名媛妹妹 2021-02-06 10:30

folks! Today I created this script that has the following functionality:

  • add new items to array
  • list all items from the array
  • remove an item from
4条回答
  •  忘了有多久
    2021-02-06 10:54

    Here is another sugestion:

    function remove(arr, index) {
      if (index >= arr.lenght) { return undefined; }
      if (index == 0) {
        arr.shift();
        return arr;
      }
    
      if (index == arr.length - 1) {
        arr.pop();
        return arr;
      }
      var newarray = arr.splice(0, index);
      return newarray.concat(arr.splice(1,arr.length))
    }
    

提交回复
热议问题