js陣列常用操作方法彙總 filter

2021-08-13 21:06:08 字數 1753 閱讀 6132

filter()的作用是返回某一陣列中滿足條件的元素,該方法返回的是乙個新的陣列

返回文字長度大於6的陣列元素

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"]

var longwords = word.filter(function(word)

)// filtered array longwords is ["exuberant", "destruction", "present"]

es 6

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"]

var longwords = words.filter(word => word.length>6)

)// filtered array longwords is ["exuberant", "destruction", "present"]

var newarray = arr.filter(callback[,thisarg])

或者 array.filter(function(currentvalue,index,arr), thisvalue)

引數(parameters)

callback:必須,陣列中的每乙個元素都會執行該函式,滿足條件的元素被返回至新陣列內,未滿足條件的被忽略。該函式預設有三個引數。

element(必選):當前元素的值

index(可選): 當前元素的索引

array(可選):當前元素所屬的陣列

thisvalue(可選):該值在callback被執行的時候使用,該值會被用作callback的this值。【if a thisarg parameter is provided to filter, it will be used as the callback』sthisvalue. 】

filter()返回乙個由滿足條件的元素組成的新的陣列

1、該例子選出陣列中大於等於10的元素

function isbigenough(value)

var filtered = [12,5,8,16,125,98].filter(isbigenough)

// filtered is [12, 130, 44]

2、該例子選出json中所有id為數字的元素

var arr = [

, ,

, ,

, ,

, ,

];var invalidentries = 0;

function isnumber(obj)

function filterbyid(item)

invalidentries++;

return false

}var arrid = arr.filter(filterbyid)

console.log(arrid);

// arrid is [, , , , ]

3、該例子根據查詢條件篩選出滿足條件的元素

function fruitsitem(query))

}console.log(fruitsitem('an'));// ['banana', 'mango', 'orange']

js常用陣列操作方法

concat 方法用於連線兩個或多個陣列。該方法不會改變現有的陣列,僅會返回被連線陣列的乙個副本。var arr1 1,2,3 var arr2 4,5 var arr3 arr1.concat arr2 console.log arr1 1,2,3 console.log arr3 1,2,3,4...

JS陣列的操作方法

var colors red blue green colors.length 計算陣列長度 array.isarray colors 檢測是否為陣列 colors.join 指定引號內的字串為分隔符 colors.push red green 推入陣列的最後 colors.pop 取得陣列的最後項...

js陣列的操作方法

向陣列的末尾新增元素返回值為當前操作的陣列的操作以後的長度 1 var arr 2,3,4,5,6,6 2 arr.push 8,9 push 新增到陣列末尾 3 console.log arr 2,3,4,5,6,6,8,9 刪除陣列的最後一項,並返回刪除元素的值 如果陣列為空則返回undefin...