JavaScript tips, updated occasionally.

Evaluates the extreme value of an array

function smallest(array){ return Math.min.apply(Math, array); } function largest(array){ return Math.max.apply(Math, array); } smallest([0, 1, 2.2, 3.3]); Largest ([0, 1, 2.2, 3.3]); / / 3.3Copy the code

The iteration the arguments

function useCall() {
    [].forEach.call(arguments, function(val, key) {
        console.log(key, val)
    });
}

useCall('Bob Dylan', 'Bob Marley', 'Steve Vai');

//0 "Bob Dylan"
//1 "Bob Marley"
//2 "Steve Vai"
Copy the code

Array.prototype.foreach () the second argument

Reference: MDN

var coder = { name: 'Shock', friends: ['Rocky', 'Bob'], logHiToFriends:function(){ 'use static' this.friends.forEach(function(friend){ console.log(this.name+ ' say hi to '+ friend); },this)// Notice this, you can guess what happens if you don't add this parameter}}Copy the code

Use IIFE to solve loop problems

unexpected:

var funcs = []; for (var i = 0; i < 10; i++) { funcs.push(function() { console.log(i); }); } funcs.forEach(function(func) { func(); // Output the value "10" ten times});Copy the code

expected:

var funcs = []; for (var i = 0; i < 10; i++) { funcs.push((function(value) { return function() { console.log(value); } }(i))); } funcs.forEach(function(func) { func(); // from 0 to 9});Copy the code

Use let to solve loop problems

This is a let unique feature (see)

var funcs = []; for (let i = 0; i < 10; i++) { funcs.push(function() { console.log(i); }); } funcs.forEach(function(func) { func(); // from 0 to 9})Copy the code

Determine if two decimals are equal

// Because javascript numbers are usually entered as decimal floating-point numbers, but are internally represented as binary numbers, the results are biased: 0.1 + 0.2 //0.30000000000000004 0.1 + 1-1 // 0.100000000000000000009 0.1 + 0.2 === 0.3 //false // So we should not directly compare non-integers, but take the upper limit, Const epsilon = math.pow (2, -53); const epsilon = math.pow (2, -53); Function epsEqu(x,y) {return Math. Abs (x-y) < EPSILON; } epsEqu (0.1 + 0.2, 0.3) / / trueCopy the code

Math.round pit of the function

Math. Round (3.2) / / - 3 Math. Round (3.5) / / - 3 (this is strange) Math. Round (3.8) / / / / - 4 actually, Math. Round (x) is equal to: Math. Floor (x + 0.5)Copy the code

Use opportunely | | and &&

var bar = $ || 233; // If $exists, assign $to bar; $=== undefined && (window.$= jQuery); // If $does not exist, jQuery is assigned to window.$; If $exists, the following expression is not executedCopy the code

Exit the loop using break + Labels

function findNumber(arr){ loop:{ for (var i = 0; i < arr.length; i++) { if(arr[i]%2 == 0){ break loop; }} console.log(arr); }} findNumber([1,3,5,6]);}} findNumber([1,3,5,6]);Copy the code

Simple implementation of merging objects

function merge(root){
  for (var i = 1; i < arguments.length; i++) {
    for (var key in arguments[i]) {
      if (object.hasOwnProperty(key)) {
        root[key] = arguments[i][key];
      }
    }
  }
  return root;
}

var merged = merge(
  {name:'Shock'},
  {city:'Shenzhen'}
)//{name:'Shock',city:'Shenzhen'}
Copy the code

Understand map and parseInt

['1','2','3'].map(parseInt); //[1, NaN, NaN] ['1','2','3'].map(function(x){return parseInt(x,10)}); / / [1, 2, 3]Copy the code

Upload image preview function

<input type="file" name="file" onchange="showPreview(this)" />
<img id="portrait" src="" width="70" height="75">
Copy the code
function showPreview(source) { var file = source.files[0]; if(window.FileReader) { var fr = new FileReader(); fr.onloadend = function(e) { document.getElementById("portrait").src = e.target.result; }; fr.readAsDataURL(file); }}Copy the code

Wechat internal modification document.title

function setTitle(title) { document.title = title; if (/ip(hone|od|ad)/i.test(navigator.userAgent)) { var i = document.createElement('iframe'); i.src = '/favicon.ico'; i.style.display = 'none'; i.onload = function() { setTimeout(function(){ i.remove(); }, 9) } document.body.appendChild(i); }} setTitle(" title to modify ");Copy the code

Quickly clone an object

var Rocker = function(name, age){ this.name = name, this.age = age } var shock = new Rocker('Shock', 24); shock.age = 99; var cloneShock = Object.create(shock); Clonessock.name // "Shock" clonessock.age // 99 // In browsers that do not support ES5, implement the create method as follows:  Object.create = Object.create || function(obj){ var F = function(){}; F.prototype = obj; return new F(); }Copy the code

Determines whether a value is an object

function isObject(value){
  return value === Object(value);
}

isObject({}); // true
isObject(123);  // false
Copy the code

This article is from Rockjins Blog, please contact the author for reprinting. Otherwise, legal liability will be investigated.