Need to delete any specified number in [1,2,3,4,5], how to do it? For example, if you want to delete 2, the result returned is [1,3,4,5]
光阴似箭催人老,日月如移越少年。
var arr=[1,2,3,4,5]; for(var i=0,len=arr.length;i<len;i++){ if(arr[i]===2){ arr.splice(i,1) } }
However, it is recommended to use the iterative method
var arr=[1,2,3,4,5]; arr.filter(function(item){return item!==2}) //es6写法 arr.filter(item =>item!==2)
arr.splice(1,1) //[1, 3, 4, 5] Delete a value with a starting subscript of 1, a length of 1, and len set to 1. If it is 0, the array remains unchanged
var e = [1,2,3,4,5] x = Math.ceil((e.length - 1) * Math.random()) console.log(x) e.splice(x, 1) console.log(e)
However, it is recommended to use the iterative method
arr.splice(1,1) //[1, 3, 4, 5] Delete a value with a starting subscript of 1, a length of 1, and len set to 1. If it is 0, the array remains unchanged