删除数组元素,自身内部改变
2019-11-19 本文已影响0人
领带衬有黄金
Js代码:
<script>
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
let i = arr.length - 1
while (i >= 0) {
if (arr[i] === 3 || arr[i] === 5 || arr[i] === 6) {
arr.splice(i, 1)
}
i--
}
console.log(arr)
</script>
Python代码:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] # 删除3,5,6
i = len(arr) - 1
while i >= 0:
if arr[i] == 3 or arr[i] == 5 or arr[i] == 6:
arr.remove(arr[i])
i -= 1
print(arr)