Some common arithmetic methods
Making the address
- The number of occurrences of each string in a string
var arr = 'abcdaabc';
var info = arr
.split(' ')
.reduce((p, k) => (p[k]++ || (p[k] = 1), p), {});
console.log(info); //{ a: 3, b: 2, c: 2, d: 1 }
Copy the code
Reduce is not very compatible with earlier versions. You can use the following method
var temp = {};
'abcdaabc'.replace(/(\w{1})/g,function(The $1){
temp[The $1]? temp[The $1]+=1 : temp[The $1] = 1; }) console. The log (temp) / / {3, a: b: 2, c: 2, d: 1} / / orfunction getTimesO(str){
var obj = {}
str.split(' ').map(function(val,index){
if(! obj[val]){ obj[val] = 1 }else{
obj[val] += 1
}
})
return obj
}
Copy the code
- Prevents events from bubbling
function stopBubble(e)
{
if (e && e.stopPropagation)
e.stopPropagation()
else
window.event.cancelBubble=true
}
Copy the code
- Determine the data type,
- typeof
Typeof variables return the data typeof the variable, but cannot distinguish between arrays and objects
- instanceof
Variable instanceof Object | | Array variable is an Array or Object, return true and false
- Array.isArray()
Array.isArray(variable) Checks whether a variable is an Array, returning true and false
- Prefix console.log () with ‘iPhone’
Wrapped log function
- A preliminary packaging
function log(){
console.log.apply(console,arguments)
}
Copy the code
- For the second encapsulation, how can I prefix the parameter
function log(){
var newArguments = []
if(arguments.length > 0){
for(var i = 0; i < arguments.length; i++){
newArguments.push('iphone',arguments[i])
}
}
console.log.apply(console,newArguments)
}
Copy the code
Or you could write it like this
function getLog() {var args = Array. Prototype. Slice. The call (the arguments) / / put the arguments pseudo Array into a true Array args. The unshift ('(app)'Console.log. apply(console,args)} getLog(console.log.apply(console,args)}'df') // (app) df
Copy the code
- Sort an array
- The first (dichotomous sort)
function sortMany(arr){
if(arr.length <= 1){
return arr
}
var left = [], right = []
var middleIndex = Math.floor(arr.length/2)
var middleValue = arr.splice(middleIndex,1)[0]
for(var i = 0; i < arr.length; i++){
if(arr[i] < middleValue){
left.push(arr[i])
}else{
right.push(arr[i])
}
}
return sortMany(left).concat(middleValue,sortMany(right))
}
Copy the code
Binary search (sorting the array first)
Var arr =,2,3,4,5,6,7 [1]function searchBinary(arr, target){
let s = 0
let e = arr.length-1
let m = Math.floor((s + e)/2)
let sortTag = arr[s] <= arr[e]
while(s < e && arr[m] ! == target){if(arr[m] > target){ sortTag && (e = m - 1) ! sortTag && (s = m + 1) }else{ sortTag && (s = m + 1) ! sortTag && (e = m -1) } m = Math.floor((s + e)/2) }if(arr[m] === target){
return m
}else{
return -1
}
}
searchBinary(arr, 3) // 2
Copy the code
- The second kind of bubble sort
function sortTwo(arr){
for(var i=0; i<arr.length-1; i++){for(var j=i+1; j<arr.length; j++){if(arr[i]>arr[j]){
var temp = arr[j]
arr[j] = arr[i]
arr[i] = temp
}
}
}
return arr
}
Copy the code
- The third kind of array built-in sort
Array.prototype.innerSort = function(){
this.sort(function (a,b){
return a - b;
})
return this
}
Copy the code
- Deduplicating the array
function deletMany(arr){
var obj = {}
var newArr = []
for(var i=0; i<arr.length-1; i++){if(! obj[arr[i]]){ newArr.push(arr[i]) obj[arr[i]] = 1 } }return newArr
}
Copy the code
- Object deep copy problem
The code is as follows to achieve a deep copy of the object
function deepCopy(p, c){
var c = c || {}
for(var i in p){
if(typeof p[i] === 'object'){
c[i] = (p[i].constructor === Array) ? [] : {}
deepCopy(p[i], c[i])
}else{
c[i] = p[i]
}
}
return c
}
Copy the code
Copying is classified into deep copy and shallow copy. Copying is to copy all the attributes of the parent object to the child object.
- A shallow copy is simply a copy of the first layer properties of the object. If there are complex data types in the first layer, it is just a copy of the pointer. If the property of the parent property changes, it will also cause the property of the copied child object to change, which is sometimes unnecessary.
- The code above implements a deep copy using a recursive implementation and can also be used
JSON.stringfy
Convert to a simple type before using itJSON.parse
To a complex type.
Another kind of deep copy of objects
function copyObject(orig){
var copy = Object.create(Object.getPrototypeOf(orig))
copyOwnPropertiesFrom(copy, orig)
return copy
}
function copyOwnPropertiesFrom(target, source){
Object
.getOwnPropertyNames(source)
.forEach(function(val){
var desc = Object.getOwnPropertyDescriptor(source, val)
if(typeof desc.value === 'object'){
target[val] = copyObject(source[val])
}else{
Object.defineProperty(target, val, desc)
}
})
return target
}
Copy the code
- Determine the type of encapsulation
let type = (o) => {
const s = Object.prototype.toString.call(o)
return s.match(/\[object (.*?)\]/)[1].toLowerCase()
}
[
"Undefiend".'Null'.'Object'.'Array'."String"."Boolean".'RegExp'.'Function'
].forEach(t => {
type['is'+ t] = (o) => {
return type(o) === t.toLowerCase()
}
});
type.isArray([]) //true
Copy the code
- Amount formatting
function toThousands(num) {
var potStr = 00 '. '
num = (num||0).toString()
if(num.indexOf('. ') !== -1){
potStr = num.substr(num.indexOf('. '),3)
}
var result = [ ], counter = 0;
num = num.substring(0,num.indexOf('. ')).split(' ');
for (var i = num.length - 1; i >= 0; i--) {
counter++;
result.unshift(num[i]);
if(! (counter % 3) && i ! = 0) { result.unshift(', '); }}return result.join(' ')+potStr;
}
Copy the code
- lazyMan
function _LazyMan(name){
this.name = name
this.quene = []
console.log('Hi This is ' + this.name)
setTimeout(() => {
this.next()
}, 0);
}
_LazyMan.prototype.next = function() {if(this.quene.length){
const fn = this.quene.shift()
if((typeof fn).toLowerCase() === 'function'){
fn()
return this
}
}else{
return this
}
}
_LazyMan.prototype.sleep = function(time){
const fn1 = () => {
setTimeout(() => {
console.log('Wake up after ' + time)
this.next()
}, time);
}
this.quene.push(fn1)
return this
}
_LazyMan.prototype.dinner = function (){
const fn = () => {
console.log('Eat dinner')
this.next()
}
this.quene.push(fn)
return this
}
function LazyMan(name){
return new _LazyMan(name)
}
LazyMan('Hank').sleep(2000).dinner()
Copy the code
- If the throttle
In the project, it is common to encounter the situation of preventing multiple clicks. In the past, a switch was used to deal with this situation. Later, we studied the method of shaking prevention and recorded it here
function debounce(fn, delay, immidate){
var timer;
return function (){
var that = this;
var args = arguments;
clearTimeout(timer)
if(immidate){// Immediately execute var heredoNow = ! timer; timer =setTimeout(function(){
timer = null
}, delay)
if(doNow){
fn.apply(that, args)
}
}else{
timer = setTimeout(function(){
fn.apply(that, args)
}, delay)
}
}
}
function foo(){
console.log('scroll timer is running')
}
document.getElementById('box').addEventListener('mousemove', debounce(foo, 2000, true))
Copy the code