开发用到的js封装方法(20种)(2)

Array.intersect = function () { var result = new Array(); var obj = {}; for (var i =0; i < arguments.length; i++) { for (var j =0; j < arguments[i].length; j++) { var str = arguments[i][j]; if (!obj[str]) { obj[str] = 1; } else { obj[str]++; if (obj[str] == arguments.length) { result.push(str); } }//end else }//end for j }//end for i return result; } console.log(Array.intersect(["1","2", "3"], ["2","3", "4", "5", "6"]))

18、数组和对象比较。取出对象的key和数组元素相同的

var arr = ['F00006','F00007','F00008']; var obj = {'F00006':[{'id':21}],'F00007':[{'id':11}]} var newobj = {}; for(var itemin obj){ if(arr.includes(item)){ newobj[item] = obj[item] } } console.log(newObj)

19、删除数组中某个元素

//第一种 Array.prototype.remove = function(val){ var index = this.indexOf(val); if(index !=0){ this.splice(index,1) } } [1,3,4].remove(3) //第二种 function remove(arr, indx) { for (var i =0; i < arr.length; i++) { var index = arr.indexOf(arr[i]); if (indx == index) { arr.splice(index, 1) } } return arr }

20、判断数组是否包含某个元素

Array.prototype.contains = function (val) { for (var i =0; i < this.length; i++) { if (this[i] == val) { return true; } } return false; }; [1, 2,3, 4].contains(2)//true

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/923f5f6bbf6fdf6de690c9def2a4eff2.html