swift 陣列的新增和刪除

2021-10-23 19:36:18 字數 2684 閱讀 7980

//: a uikit based playground for presenting user inte***ce

import uikit

var array = [(42,"erro2"),(41,"erro1"),(43,"erro3")]

print(array)

[(42, "erro2"), (41, "erro1"), (43, "erro3"), (40, "error0"), (42, "erro2"), (41, "erro1")]

同理也有

insert(_:at:) 在指定位置插入乙個元素

insert(contentsof:at)在指定位置插入多個元素

//: a uikit based playground for presenting user inte***ce

import uikit

var array = [(42,"erro2"),(41,"erro1"),(43,"erro3")]

array.insert((40,"error0"),at: 0)

array.insert(contentsof: [(42,"erro2"),(41,"erro1")],at: array.endindex)

print(array)

[(40, "error0"), (42, "erro2"), (41, "erro1"), (43, "erro3"), (42, "erro2"), (41, "erro1")]

字串也是collection

字串也是collection element時character型別

["d", "e", "f", "g", "h", "a", "b", "c"]

remove(at:)移除並返回指定位置的乙個元素

removefirst()移除並返回陣列的第乙個元素

popfirst() 移除並返回陣列的第乙個元素(optional),陣列為空返回nil.

//: a uikit based playground for presenting user inte***ce

import uikit

var chars:[character] = ["a","b","c","d"]

print(chars)

let removedchar = chars.remove(at: 1)

print(removedchar)

print(chars)

let removedchar2 = chars.removefirst()

print(removedchar2)

print(chars)

結果

["a", "b", "c", "d"]

b["a", "c", "d"]

a["c", "d"]

removefirst(:) 移除前面多個元素

removelist(:)移除後面多個元素

//: a uikit based playground for presenting user inte***ce

import uikit

var chars:[character] = ["a","b","c","d"]

chars.removefirst(2)

print(chars)

chars.removelast(2)

print(chars)

["c", "d"]

removesubrange(_:)移除陣列中給定範圍的元素

removeall() 移除陣列所有元素

removeall(keepingcapacity:)移除所有元素,保留陣列容量

//: a uikit based playground for presenting user inte***ce

import uikit

var chars:[character] = ["a","b","c","d"]

chars.removesubrange(1...2)

print(chars)

chars.insert(contentsof: "bc", at: 1)

print(chars)

chars.removeall()

print(chars)

print(chars.capacity)

chars.insert(contentsof: "abcd", at: 0)

print(chars)

chars.removeall(keepingcapacity: true)

print(chars)

print(chars.capacity)

["a", "d"]

["a", "b", "c", "d"]

0["a", "b", "c", "d"]

4

js陣列的新增和刪除

js中陣列元素常用新增方法是直接新增 push方法以及unshift方法 刪除方法則是delete pop shift 集修改方法為一身的則是splice 1 新增 1 直接新增通常都是這樣 var arr arr 0 first arr 1 second 2 push push方法向陣列的末尾新增...

js 陣列的新增和刪除方法

1.shift 方法 把陣列的第乙個元素刪除,並返回刪除的元素值。會改變原陣列 var movepos 11,22 movepos.shift console.log movepos 22 alert movepos 22 document.write movepos.length 1 2.conc...

新增和刪除陣列元素

1.在陣列頭新增元素 array unshift 使用該函式,所有已有的數值鍵都會相應的修改,以反映騎在陣列中的新位置,但是關聯鍵不受影響。names array tom jack jerry array unshift names,amy job names array amy job tom j...