JS common method function

  javascript

JS common method function

  1. String length truncation
  2. Inert evaluation
  3. closure
  4. Basic Package Type (Package Object)
  5. Object traversal (best method)
  6. Array traversal (built-in method)
  7. How do you determine whether an object is an array?
  8. Addition table
  9. Sort method
  10. Prefix specification
  11. Douglas’ object method (equivalent to the object.create method)

1. String length interception

function cutstr(str, len) {
    var temp,
        icount = 0,
        patrn = /[^\x00-\xff]/,
        strre = "";

    for (var i = 0; i < str.length; i++) {
        if (icount < len - 1) {
            temp = str.substr(i, 1);
            if (patrn.exec(temp) === null) {
                icount += 1;
            } else {
                icount += 2;
            }
            strre += temp;
        } else {
            break;
        }
    }
    return strre + "...";
}

2. Inert evaluation

const range = function* (from, to) {
    for (let i = from; i < to; i++) {
        console.log('range\t', i);
        yield i;
    }
};

const map = function* (flow, transform) {
    for (const data of flow) {
        console.log('map\t', data);
        yield (transform(data));
    }
};

const filter = function* (flow, condition) {
    for (const data of flow) {
        console.log('filter\t', data);
        if (condition(data)) {
            yield data;
        }
    }
};

const stop = function* (flow, condition) {
    for (const data of flow) {
        yield data;
        if (condition(data)) {
            break;
        }
    }
};

const take = function (flow, num) {
    let count = 0;
    const _filter = function (data) {
        count++;
        return count >= num;
    };
    return stop(flow, _filter);
};

class _Lazy {
    constructor() {
        this.iterator = null;
    }

    range(...args) {
        this.iterator = range(...args);
        return this;
    }

    map(...args) {
        this.iterator = map(this.iterator, ...args);
        return this;
    }

    filter(...args) {
        this.iterator = filter(this.iterator, ...args);
        return this;
    }

    take(...args) {
        this.iterator = take(this.iterator, ...args);
        return this;
    }

    [Symbol.iterator]() {
        return this.iterator;
    }
}

function lazy() {
    return new _Lazy();
}

const nums = lazy().range(0, 100).map(n => n * 10).filter(n => n % 3 === 0).take(2);
for (let n of nums) {
    console.log('num:\t', n, '\n');
}

Closure

const Greeters = [];

//方法一
for (let i = 0; i < 10; i++) {
    Greeters.push(function () {
        return console.log(i);
    })
}
//方法二
for (var i = 0; i < 10; i++) {
    Greeters.push(console.log.bind(null, i))
}
Greeters[0]();//0
Greeters[1]();//1
Greeters[2]();//2

4. Inert evaluation

var s1 = "hello world";
var s2 = s1.substr(4);

ECMAScriptThree special reference types are also providedBoolean,String,Number. We call these three special reference types basic package types, also called package objects.

That is to say, when readingstring,booleanAndnumberWhen these three basic data types are used, the background will create a corresponding basic wrapper type object so that we can call some methods to manipulate the data.

So when the second line of code accessess1, the background will automatically complete the following operations:

  1. CreateStringAn instance of the type; //var s1 = new String(“helloworld”);
  2. Calls the specified method on the instance; //var s2 = s1.substr(4);
  3. Destroy this example; //s1 = null;

Because of the third step of destruction, you should be able to understand why attributes and methods cannot be added to basic data types, which is the main difference between basic package types and reference types:The lifetime of the object.

UsenewInstances of reference types created by operators are stored in memory until the execution stream leaves the current scope. However, objects of basic package type created automatically only exist at the moment of execution of one line of code, and then are destroyed immediately.

5. Object traversal (best method)

//为 Object 设置三个自定义属性(可枚举)
Object.prototype.userProp = 'userProp';
Object.prototype.getUserProp = function () {
    return Object.prototype.userProp;
};

//定义一个对象,隐式地继承自 Object.prototype
var obj = {
    name: 'percy',
    age: 21,
    [Symbol('symbol 属性')]: 'symbolProp',
    unEnumerable: '我是一个不可枚举属性',
    skills: ['html', 'css', 'js'],
    getSkills: function () {
        return this.skills;
    }
};

//设置 unEnumerable 属性为不可枚举属性
Object.defineProperty(obj, 'unEnumerable', {
    enumerable: false
});

//利用 Object.create() 新建一个对象,并且这个对象没有任何原型链
var obj2 = Object.create(null, {
    name: {value: 'percy'},
    age: {value: 21},
    skills: {value: ['html', 'css', 'js']}
});
/*
* 针对上面的情况,我们用一个更完善的解决方案来解决。
* 使用 Object.prototype.hasOwnProperty.call(obj,’prop’…)
* */
Object.prototype.hasOwnProperty.call(obj2, 'name');//true
Object.prototype.hasOwnProperty.call(obj2, 'skills');//true
Object.prototype.hasOwnProperty.call(obj2, 'userProp');//false

6. Array traversal (built-in method)

Array.prototype.forEach(): Performs the provided function once for each element of the array

//如果数组在迭代时被修改了,则按照索引继续遍历修改后的数组
var words = ["one", "two", "three", "four"];
words.forEach(function (word) {
    console.log(word);
    if (word === 'two') {
        words.shift();
    }
});

Array.prototype.map(): returns a new array, each element being the value returned by the callback function

// map 的一个坑
[1,2,3].map(parseInt);//[1, NaN, NaN]

Some useful array built-in methods

  • Array.prototype.every(callback[,thisArg]): Test whether each element of the array has passed the test of the callback function, and if so, returntrue, otherwise returnfalse(Essentially, if the callback function returns a value oftrueIf so, thenevery()Returntrue, otherwise,false)
  • Array.prototype.filter(callback[,thisArg]): returns a new array whose elements are the tested elements in the original array (that is, the callback function returnstrueIf so, the corresponding elements will enter the new array)
  • Array.prototype.find(callback[,thisArg]): Returns the first element that passed the test
  • Array.prototype.findIndex(callback[,thisArg]): similar to the above function except that this is the return index
  • Array.prototype.some(callback[,thisArg]): similarfind(), except that it does not return elements, only oneBoolean value. As long as one passes the test, it will returntrue
  • Array.prototype.reduce(callback,[initialValue])It is customarily calledAccumulator functionFor each element of the arrayExecute callback function, and finally returns a value that was returned the last time the callback function was called

The callback function of this function has 4 parameters

  1. accumulator: The value returned by the last call to the callback function
  2. currentValue: The value currently being processed
  3. currentIndex
  4. array

initialValue: optional, whose value is used for the first callcallbackThe first parameter of the

  • Array.prototype.reduceRight(callback[, initialValue])The usage is the same as the function above, except that the traversal direction is just the opposite.

Summarize the commonness of the above functions

  • The logic operation or judgment is carried out through the return value of each callback function.
  • Callback functions can be written as more concise arrow functions (recommended)
  • Can pass the shape such asArray.prototype.map.call(str,callback)To manipulate strings using the

7. how to judge whether an object is an array

Method 1:UseObject.prototype.toStringTo determine whether it is an array

function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
}

Used herecallTo maketoStringInthispoint toobjTo complete the judgment.

Method 2:UsePrototype chainTo complete the judgment

function isArray(obj) {
    return obj.__proto__ === Array.prototype;
}

The basic idea is to use an instance if it is constructed by a constructor, then its__proto__Pointing to the constructorprototypeProperty.

Method 3:utilizeJQuery

function isArray(obj){
    return $.isArray(obj)
}

JQuery isArrayThe realization of is actually method one.

8. Addition Operation Table

  • Number+Number-> addition
  • Boolean+Number-> addition
  • Boolean+Boolean-> addition
  • Number+String-> connection
  • String+Boolean-> connection
  • String+String-> connection

9. Sorting method

Bubble sort

function bubbleSort(arr) {
    var len = arr.length;
    for (var i = 0; i < len - 1; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}

Selection sort

  1. First, find the smallest (largest) element in the unsorted sequence and store it in the starting position of the sorted sequence.
  2. Then continue to look for the smallest (largest) element from the remaining unsorted elements and place it at the end of the sorted sequence.
  3. Repeat the second step until all elements are sorted
function selectionSort(arr) {
    var len = arr.length,
        minIndex, temp;

    for (var i = 0; i < len - 1; i++) {
        minIndex = i;
        for (var j = i + 1; j < len; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
    return arr;
}

Insertion sort

  1. First, find the smallest (largest) element in the unsorted sequence and store it in the starting position of the sorted sequence.
  2. Scan the unordered sequence from beginning to end, and insert each scanned element into the appropriate position of the ordered sequence. (If the element to be inserted is equal to an element in the ordered sequence, the element to be inserted is inserted after the equal element. )
function insertionSort(arr) {
    var len = arr.length,
        preIndex, current;

    for (var i = 1; i < len; i++) {
        preIndex = i - 1;
        current = arr[i];
        while (preIndex >= 0 && arr[preIndex] > current) {
            arr[preIndex + 1] = arr[preIndex];
            preIndex--;
        }
        arr[preIndex + 1] = current;
    }
    return arr;
}

merge sort

The basic principle is the divide-and-conquer method, which is to sort separately and recursively.

  1. The application space is the sum of two ordered sequences, and the space is used for storing the merged sequences.
  2. Setting two pointers, the initial positions of which are respectively the initial positions of two ordered sequences;
  3. Comparing the elements pointed by the two pointers, selecting the relatively small element to put into the merging space, and moving the pointer to the next position;
  4. Repeat step 3 until a pointer reaches the end of the sequence;
  5. Copy all remaining elements of another sequence directly to the end of the merge sequence.
function insertionSort(arr) {
    var len = arr.length,
        preIndex, current;

    for (var i = 1; i < len; i++) {
        preIndex = i - 1;
        current = arr[i];
        while (preIndex >= 0 && arr[preIndex] > current) {
            arr[preIndex + 1] = arr[preIndex];
            preIndex--;
        }
        arr[preIndex + 1] = current;
    }
    return arr;
}

10. Prefix Specification

Each local variable needs a type prefix, which can be divided into:

S: represents a string. For example: sName, sHtml;;
N: indicates a number. For example: nPage, nTotal;;
B: it means logic. For example: bChecked, bHasLogin;;
A: represents an array. For example: aList, a group;
R: Represents a regular expression. For example, rDomain, rEmail;;
F: represents a function. For example: fGetHtml, fInit;;
O: Indicates other objects not covered above, such as: oButton, oDate;;
G: represents a global variable, for example: gUserName, gLoginTime;;

11. Douglas’s object method (equivalent to object.create method)

function object(o) {
    var F = function () {
    };
    F.prototype = o;
    return new F();
}