亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

刪除JavaScript中的數組元素-刪除VS拼接

刪除JavaScript中的數組元素-刪除VS拼接

慕桂英3389331 2019-05-31 16:47:03
刪除JavaScript中的數組元素-刪除VS拼接使用這個delete操作者在數組元素上,而不是使用這個Array.splice方法?例如:myArray = ['a', 'b', 'c', 'd'];delete myArray[1];//  ormyArray.splice (1, 1);如果我可以像刪除對象一樣刪除數組元素,那么為什么還要使用Splice方法呢?
查看完整描述

4 回答

?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

delete將刪除對象屬性,但不會重新索引數組或更新其長度。這使它看起來似乎是未定義的:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]> delete myArray[0]
  true> myArray[0]
  undefined

注意,它實際上沒有設置為undefined,而是將屬性從數組中移除,使其成為出現沒有定義。Chrome dev工具通過打印明確了這一區別。empty記錄數組時。

> myArray[0]
  undefined> myArray  [empty, "b", "c", "d"]

myArray.splice(start, deleteCount)實際上移除元素,重新索引數組,并更改其長度。

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]> myArray.splice(0, 2)
  ["a", "b"]> myArray  ["c", "d"]


查看完整回答
反對 回復 2019-05-31
?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

Array.emove()方法

約翰·雷西格,jQuery的創建者創建了一個非常方便的Array.remove方法,以便在項目中始終使用它。

// Array Remove - By John Resig (MIT Licensed)Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);};

下面是一些如何使用它的例子:

// Remove the second item from the arrayarray.remove(1);// Remove the second-to-last item from the arrayarray.remove(-2);
// Remove the second and third items from the arrayarray.remove(1,2);
// Remove the last and second-to-last items from the arrayarray.remove(-2,-1);

約翰網站


查看完整回答
反對 回復 2019-05-31
?
元芳怎么了

TA貢獻1798條經驗 獲得超7個贊

因為DELETE只從數組中的元素中刪除對象,所以數組的長度不會改變。Splice移除對象并縮短數組。

下面的代碼將顯示“a”、“b”、“未定義”、“d”

myArray = ['a', 'b', 'c', 'd']; delete myArray[2];for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);}

而這將顯示“a”、“b”、“d”

myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);}


查看完整回答
反對 回復 2019-05-31
?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

我無意中發現了這個問題,同時試圖理解如何從Array中刪除每個元素的出現。下面是一個比較splicedelete為了移除每一個'c'items陣列。

var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];while (items.indexOf('c') !== -1) {
  items.splice(items.indexOf('c'), 1);}console.log(items);
   // ["a", "b", "d", "a", "b", "d"]items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];while (items.indexOf('c') !== -1) {
  delete items[items.indexOf('c')];}console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]


查看完整回答
反對 回復 2019-05-31
  • 4 回答
  • 0 關注
  • 727 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號