簡體   English   中英

array.splice()給出錯誤TypeError:arr.splice不是一個函數(…)

[英]array.splice() gives error TypeError: arr.splice is not a function(…)

var arr = document.querySelectorAll("a[href*='somestring']")

返回控制台中看起來像數組的內容。 方括號[]和arr.length = 7。

屏幕如下。 為什么splice()在我的數組上不起作用? 在此處輸入圖片說明

querySelectorAll返回的對象是NodeList ,它類似於 Array,但不是實際的數組。

嘗試將其轉換為數組:

[].slice.call(document.querySelectorAll("a[href*='somestring']"));

https://developer.mozilla.org/zh-CN/docs/Web/API/NodeList

HTMLCollectionNodeList對象沒有splice方法,也不繼承自Array.prototype

此外,你不能簡單地調用拼接上他們,因為他們不是在設計,即使它們是類似數組進行修改。

首先,將它們轉換為真正的Array

var arr = document.querySelectorAll("a[href*='somestring']"); // NodeList
arr = Array.prototype.slice.call(arr); // Array
arr.splice(2, 2); // splicing an Array

document.querySelectorAll("a[href*='somestring']")返回一個不是數組的對象。

嘗試將其轉換為數組:

var arr = document.querySelectorAll("a[href*='somestring']");

var a = [];
for(var i =0;i<arr.length ; i++){
a[i] = arr[i];
} 

a.splice()//now you can use a as an array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM