JavaScript language essence - reading notes (3)

Chapter VI Array

And an array in JS objects are objects in real terms, property is an array of consecutive integers. typeof (Array) = 'object'

// 判断数组的方法
var is_array = function(value) {
  return value && typeof value === 'object' && value.constructor === Array;
};
// 不足:识别不同的window或者frame失败

//改进方法
var is_array = function(value) {
  return Object.prototype.toString.apply(value) === '[object Array]';
}

Method Array.prototype stored in the array, the object can be expanded Object.prototype prototype array of methods may also be expanded.

Array.method('reduce', fucntion(f, value){
  for (let i = 0; i < this.length; i ++){
    value = f(this[i], value);
  }
  return value;
});
// 给数组扩展方法:传入一个函数和初始值,对数组的每一项运行函数。下面是实际案例。
let data = [1, 2, 3, 4];
var add = function(a, b) {
  retunr a + b;
}
var mult = function(a, b) {
  retunr a * b;
}
var sum = data.reduce(add, 0);
// 将数组执行add方法,初始值是0
var prodect = data.reduce(mult, 1);
// 将数组执行mult方法,初始值是1

A landmark array by setting attributes, and can set the properties directly using dot syntax. It can be said, array.length dot syntax is similar object.

JS array has no multi-dimensional arrays, support elements for the array of arrays, where we construct a matrix.

Array.matrix = function(m, n, init) {
  var mat = [];
  for (var i = 0; i < m; i++) {
    a = [];
    for (var j = 0; j < n; j++) {
      a[j] = initial;
    }
    mat[i] = a;
  }
  return mat;
}

var myMatrix = Array.matrix(4, 4, 0);
document.writeLn(myMatrix);
// 生成一个0填充的 4*4 的矩阵。

// 单位矩阵
Array.identity = function(n) {
  let mat = Array.matrix(n, n, 0);
  for (let i = 0; i < n; i++) {
    mat[i][i] = 1;
  }
  return mat;
};
myMatrix = Array.identity(4);
document.writeln(myMatrix[3][3]);

Chapter VII Regular Expressions

Regular expressions writing very complex, post-maintenance is relatively complex. Best time to write a short and pithy.

var parse = /^(?:[A-Za-z]+)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;

// 划分网址

Chapter IX method

Array

Array.concat plurality of arrays, variables into a new array. The array is an array of shallow copy, and insert other elements or array back to the new array.

Array.join (seperator) connecting the different elements of the array into a string, the principle is to convert each into a string, to connect these strings.

Array.pop () out of the last element in the array and returns (similar to stack Stack), if the array is empty, then returns undefined.

Array.push (item1, item2) adding a last element in the array to change the original array, the return value is the length of the new array.

Array.reverse () array flip back and forth, the original array into a new array, the return value is the new array.

Array.shift () out of the first array element (empty array undefined) shift speed much slower than pop.

array.unshift increase in the first element, the return value is the length of the new array

Part array.slice (a, b) shallow copy of the array, is behind the front opening and closing zone interview segment; if only one parameter, this parameter indicates a copy from the end of the array. => Part of the old array replication

The Array.sort () to sort strings: a string may be sorted, not directly to sort the array (the array is first converted to a string, the string comparison, usually an error); Of course, on this basis, to increase or a method of sorting objects ordered array.

Array.splice (a, b, c) remove a portion of the array: the array of position a, b deleting elements, added elements c. (C optional)

var a = [1, 2, 3];
var b = [4, 5, 6];
var c = a.concat(b, true);
a.push(6,7); // 这里改变数组a, 不会影响新的数组c。因为已经产生了新的数组c。
console.log(c);
// [1,2,3,4,5,6,true]

Function

// function.apply 传递一个绑定到 this 上的对象和一个可选的数组作为参数。
Function.method('bind', function(that) {
  // 返回一个函数。调用这个函数就是调用这个对象的一个方法
  var method = this;
  var slice = Array.prototype.slice;
  var args = slice.apply(arguments, [1]);
  return function() {
    return method.apply(that,
      args.concat(slice.apply(arguments, [0])));
  };
});

let x = function() {
  return this.value;
}.bind({ value: 666 });

alert(x());

call and apply the array: a method of an object on top of another object, another object can use these methods.

Obj1.method1.call (Obj2, para1, para2); object having method1 method, but no object2 method1 method. So here Object2 borrow method method object1 and then passed two parameters, inherit.

Obj1.method2.apply (Obj2, [para1, para2]) apply passed parameter is an array, other similar functions and effects.

See call.js Code

Number

Values ​​into a different character string several methods

// toExponential() 转换成一个指数形式的字符串;
Math.PI.toExponential(2); // 3.14e+0

// toFixed 转化成一个十进制数的字符串,参数是小数点后的位数
Math.PI.toFixed(5); // 3.14159

// toPrecision 转化成一个十进制的字符串,参数是数字的精度
Math.PI.toPrecision(3); // 3.14

// toString(16) 转化成一个字符串,参数是转换的进制,默认是10
Math.PI.toSting();
Object

This method can object.hasOwnProperty attribute of the object, but the same name attribute not checked prototype chain;

var a = {isLoading: true};
a.hasOwnProperty('isLoading') => true

var b = Object.create(a);
// 创建一个新对象b,其中的__proto__ 就是a, b对象可以访问a对象原型链上的方法和属性
b.hasOwnProperty('isLoading') => false
console.log(b.isLoading) => true
RegExp Regular Expressions

exec

The most powerful slowest method for matching strings. If the regular expression match, it returns an array, the array of different items that packet capture text. If the match fails, it will return null. If the global retrieval g, does not find the string from the starting position, but starting from regexp.lastIndex. If another query, we need to regexp.lastIndex reset to 0.

// 将HTML文本分解成标签和文本
var text = '<html><body bgcolor=linen><p>' + '</p></body></html>';
var tags = /[^<>]+|<(\/?)([A-Za-z]+)([^<>*])>/g;
var a, i ;

while ((a = tags.exec(text))) {
  for (i = 0; i < a.length; i++) {
    console.log((i + a[i]).entityify());
  }
}

test

It matches the regular expression of the most short-answer method, if the regular expression matching string, returns a Boolean value, can not use the global identifier g.

var b = /&.+/.test('Tom &amp; beans');
RegExp.method('test', function(string) {
  return this.exec(string) !== null;
});
string

The method of the string is the most commonly used method

string.charAt(position); // 返回字符串中某个位置的字符,如果位置超过长度或者是负数,那么返回一个空字符串
string.charCodeAt(pos); // return 字符码位 if(pos > string.length) return NaN
string.concat('a', 'b'); //通常直接加号链接字符串即可
string.indexOf('test', 10); // 从位置10开始检错,查询test字符串,返回第一个匹配字符的位置,找不到返回-1
string.lastIndexOF('test', 3); // 从末尾开始查找
string.match(regexp) //让字符串和一个正则表达式进行匹配,依据g标识来决定怎样进行分配。如果没有g, string.match(regexp) 和 regexp.exec(string) 结果相同。如果regexp具有g标识,那么返回一个匹配的数组。
string.replace('search', 'replace'); // 如果标明g,就是替换第一个匹配的字符。
string.search(regexp); // 类似于indexOf 传入的参数是正则表达式,返回第一个匹配字符的首字符位置(没有position参数)
var text = 'hello world "anynone" tall';
var position = text.search(/["']/);

string.slice(start, end); // 复制string的一部分构造一个新的字符串。如果是负数,就从后面开始;默认end是string.length.
string.split(seperator, limit); // 将字符串按照分隔符分割成片段,并创建一个字符串数组。limit表示分割片段的数量。分隔符可以使字符串或者是正则表达式。如果分隔符是空字符,返回单字符的数组。

var ip = '192.168.0.1';
var b = ip.slice('.'); // ['192', '168', '0', '1']

string.toLowerCase();
string.toUpperCase();
string.fromCharCode(char...); //根据数字编码创建一个字符串 

截取一个字符串的方法:最好使用slice, 不要使用substring 因为后者无法使用负数;

Chapter IX coding style

JS code format Do not ask, fault tolerance is very high, which could cause bug. Write a brace if possible to avoid the scope of. Write appropriate notes and update annotation (code updates, comments also need to be updated). Detailed coding style can refer to "the code clean of the Road" book.

Chapter X beautiful features

Function is a top-level object

Function closure (the lambda) having a lexical scope

Dynamic object prototype inheritance

The object is no category. An object can add a new member properties by ordinary assignment; an object can inherit property from a member of another object.

Object literals and array literals

Convenient to create objects and arrays (from JSON)

Guess you like

Origin blog.csdn.net/weixin_41697143/article/details/90706276