js数组查找是否包含方法总结

JavaScript08

js数组查找是否包含方法总结,第1张

var arr = [1, 2, 3, 4, 5, 6]

方法一: indexOf (常用)

if (arr.indexOf(2) !== -1) { console.log("包含2") }

方法二: find() 该方法用于查找符合条件的第一个元素,如果找到了,返回这个元素,否则,返回undefined

if (arr.find(item =>item === 2)) { console.log("包含2") }

方法三: findIndex()   和find()类似,也是查找符合条件的第一个元素,不同之处在于findIndex()会返回这个元素的索引,如果没有找到,返回-1

if (arr.findIndex(item =>item === 2) !== -1) { console.log("包含2") }

方法四: some()  查找复合条件的元素, 如果查找到返回true, 反之false

if (arr.some(item =>item === 2) { console.log("包含2") }

方法五: 循环遍历 如map, forEach, if()等等, 此处只用forEach举例

aa.forEach(item =>{if (item === 2) {console.log("包含2")}})

原生js的数组是不包含去重函数的。

可以自己编写去重函数。

下面是一个简单的例子

$.array.extend({

    unique : function (fn) {

        var len = this.length,

            result = this.slice(0),

            i, datum

             

        if ('function' != typeof fn) {

            fn = function (item1, item2) {

                return item1 === item2

            }

        }

        

        while (--len > 0) {

            datum = result[len]

            i = len

            while (i--) {

                if (fn(datum, result[i])) {

                    result.splice(len, 1)

                    break

                }

            }

        }

 

        len = this.length = result.length

        for ( i=0 i<len i++ ) {

            this[ i ] = result[ i ]

        }

 

        return this

    }

})