原生JS forEach和map遍历的区别以及兼容写法

JavaScript018

原生JS forEach和map遍历的区别以及兼容写法,第1张

forEach 没有返回值,map 有返回值。

if ( !Array.prototype.forEach ) {

Array.prototype.forEach = function forEach( callback, thisArg ) {

var T, k

if ( this == null ) {

throw new TypeError( "this is null or not defined" )

}

var O = Object(this)

var len = O.length >>> 0 

if ( typeof callback !== "function" ) {

throw new TypeError( callback + " is not a function" )

}

if ( arguments.length > 1 ) {

T = thisArg

}

k = 0

while( k < len ) {

var kValue

if ( k in O ) {

kValue = O[ k ]

callback.call( T, kValue, k, O )

}

k++

}

}

}

if (!Array.prototype.map) {

    Array.prototype.map = function(callback, thisArg) {

        var T, A, k

        if (this == null) {

            throw new TypeError(" this is null or not defined")

        }

        var O = Object(this)

        var len = O.length >>> 0

        if (typeof callback !== "function") {

            throw new TypeError(callback + " is not a function")

        }

        if (thisArg) {

            T = thisArg

        }

        A = new Array(len)

        k = 0

        while(k < len) {

            var kValue, mappedValue

            if (k in O) {

                kValue = O[ k ]

                mappedValue = callback.call(T, kValue, k, O)

                A[ k ] = mappedValue

            }

            k++

        }

        return A

    }

}

使用JS写个Map很容易,但是想要HashMap估计有困难.不知道你是否只是想要个Map还是指定HashMap.以下代码是一个普通的Map:

function Map() {

var struct = function(key, value) {

this.key = key

this.value = value

}

var put = function(key, value){

for (var i = 0i <this.arr.lengthi++) {

if ( this.arr[i].key === key ) {

this.arr[i].value = value

return

}

}

this.arr[this.arr.length] = new struct(key, value)

}

var get = function(key) {

for (var i = 0i <this.arr.lengthi++) {

if ( this.arr[i].key === key ) {

return this.arr[i].value

}

}

return null

}

var remove = function(key) {

var v

for (var i = 0i <this.arr.lengthi++) {

v = this.arr.pop()

if ( v.key === key ) {

continue

}

this.arr.unshift(v)

}

}

var size = function() {

return this.arr.length

}

var isEmpty = function() {

return this.arr.length <= 0

}

this.arr = new Array()

this.get = get

this.put = put

this.remove = remove

this.size = size

this.isEmpty = isEmpty

}