常用javascript函数

来源:互联网 发布:2015网络流行口头禅 编辑:程序博客网 时间:2024/05/21 06:46

isAlien(a)Internet Explorer holds references to objects which are not JavaScript objects, and which produce errors if they are treated as JavaScript objects. This is a problem because typeof identifies them as JavaScript objects. The isAlien() function will return true if a is one of those alien objects.

isArray(a)isArray() returns true if a is an array, meaning that it was produced by the Array constructor or by using the [ ] array literal notation.

isBoolean(a) isBoolean(a) returns true if a is one of the boolean values, true or false.

isEmpty(a) isEmpty(a) returns true if a is an object or array or function containing no enumerable members.

isFunction(a)isFunction(a) returns true if a is a function. Beware that some native functions in IE were made to look like objects instead of functions. This function does not detect that.

isNull(a)isNull(a) returns true if a is the null value.

isNumber(a)isNumber(a) returns true if a is a finite number. It returns false if a is NaN or Infinite. It also returns false if a is a string that could be converted to a number.

isObject(a) isObject(a) returns true if a is an object, and array, or a function. It returns false if a is a string, a number, a boolean, or null, or undefined.

isString(a) isString(a) returns true if a is a string.

isUndefined(a) isUndefined(a) returns true if a is the undefined value. You can get the undefined value from an uninitialized variable or from a missing member of an object.

String MethodsJavaScript provides some useful methods for string objects, but leaves out some important ones. Fortunately, JavaScript allows us to add new methods to the basic types.

entityify()entityify() produces a string in which '<', '>', and '&' are replaced with their HTML entity equivalents. This is essential for placing arbitrary strings into HTML texts. So,

"if (a < b && b > c) {".entityify()

produces

"if (a &lt; b &amp;&amp; b &gt; c) {"

quote()quote() produces a quoted string. This method returns a string which is like the original string except that it is wrapped in quotes and all quote and backslash characters are preceded with backslash.

supplant(object)supplant() does variable substitution on the string. It scans through the string looking for expressions enclosed in { } braces. If an expression is found, use it as a key on the object, and if the key has a string value or number value, it is substituted for the bracket expression and it repeats. This is useful for automatically fixing URLs. So

param = {domain: 'valvion.com', media: 'http://media.{domain}/'};url = "{media}logo.gif".supplant(param);produces a url containing "http://media.valvion.com/logo.gif".

trim()The trim() method removes whitespace characters from the beginning and end of the string.

Function MethodsIn Classical Inheritance in JavaScript, we added some useful methods to function objects for describing class/method relationships. We want to include those in our toolkit. We also need an apply() method. Most browsers provide it but some do not.

apply(object, args) apply() is a method of a function which calls the function as though it is a method of the object. The this variable will be bound to the object. args is an optional array of values which will be used as the function's arguments.

Array MethodsThese array methods are required by the ECMAScript Specification, but they did not make it into IE 5.0, so we will add them ourselves. The push and pop methods allow use to use an array as a stack. The shift and unshift methods allow us to use an array as a double-ended queue. The splice method allows us to use an array as a string of values.All of these methods modify the array.

JavaScript arrays are implemented as hashtables, but when using these methods, it is easier to think about traditional arrays, which are a contiguous series of numbered slots.

pop()The pop() method removes the last item from an array and returns it.

push(a...)The push() method appends one or more elements to the end of an array. The new length of the array is returned.

shift()The shift() method removes the [0] element from the array and returns it. It also reduces the subscripts of all of the remaining elements in the array by one.

splice(start, deleteCount, a...)The splice() method deletes elements starting at the start index, and inserts new elements at the same point. It returns an array containing the deleted values. Do not confuse the splice() method with the slice() method or the split() method.

unshift(a...)The unshift() method inserts new elements to the beginning of an array. The new length of the array is returned.

DeploymentYou can put these functions in your code library and copy them individually into your projects as you need them. Or you can put them all in a single file that you include in all of your projects, so you can always count on having a familiar platform to work from. Be sure to process the file with JSMIN in order to reduce download time. You may have useful toolkit functions if your own to include. I like to include the Classical Inheritance methods, for example.

SourceIn the source code that follows, the priorities were portability and compactness. There are faster formulations for some of the array methods, but the intention was to make them work on IE 5.0 without loading too much unnecessary code into more competent browsers.

function isAlien(a) {   return isObject(a) && typeof a.constructor != 'function';}function isArray(a) {    return isObject(a) && a.constructor == Array;}function isBoolean(a) {    return typeof a == 'boolean';}function isEmpty(o) {    var i, v;    if (isObject(o)) {        for (i in o) {            v = o[i];            if (isUndefined(v) && isFunction(v)) {                return false;            }        }    }    return true;}function isFunction(a) {    return typeof a == 'function';}function isNull(a) {    return typeof a == 'object' && !a;}function isNumber(a) {    return typeof a == 'number' && isFinite(a);}function isObject(a) {    return (a && typeof a == 'object') || isFunction(a);}function isString(a) {    return typeof a == 'string';}function isUndefined(a) {    return typeof a == 'undefined';} String.    method('entityify', function () {        return this.replace(/&/g, "&amp;").replace(/</g,            "&lt;").replace(/>/g, "&gt;");    }).    method('quote', function () {        var c, i, l = this.length, o = '"';        for (i = 0; i < l; i += 1) {            c = this.charAt(i);            if (c >= ' ') {                if (c == '//' || c == '"') {                    o += '//';                }                o += c;            } else {                switch (c) {                case '/b':                    o += '//b';                    break;                case '/f':                    o += '//f';                    break;                case '/n':                    o += '//n';                    break;                case '/r':                    o += '//r';                    break;                case '/t':                    o += '//t';                    break;                default:                    c = c.charCodeAt();                    o += '//u00' + Math.floor(c / 16).toString(16) +                        (c % 16).toString(16);                }            }        }        return o + '"';    }).    method('supplant', function (o) {        var i, j, s = this, v;        for (;;) {            i = s.lastIndexOf('{');            if (i < 0) {                break;            }            j = s.indexOf('}', i);            if (i + 1 >= j) {                break;            }            v = o[s.substring(i + 1, j)];            if (!isString(v) && !isNumber(v)) {                break;            }            s = s.substring(0, i) + v + s.substring(j + 1);        }        return s;    }).    method('trim', function () {        return this.replace(/^/s*(/S*(/s+/S+)*)/s*$/, "$1");    }); The functions that follow will be ignored unless they are needed. If there is already a suitable method, we use it.

if (!isFunction(Function.apply)) {    Function.method('apply', function (o, a) {        var r, x = '____apply';        if (!isObject(o)) {            o = {};        }        o[x] = this;        switch ((a && a.length) || 0) {        case 0:            r = o[x]();            break;        case 1:            r = o[x](a[0]);            break;        case 2:            r = o[x](a[0], a[1]);            break;        case 3:            r = o[x](a[0], a[1], a[2]);            break;        case 4:            r = o[x](a[0], a[1], a[2], a[3]);            break;        case 5:            r = o[x](a[0], a[1], a[2], a[3], a[4]);            break;        case 6:            r = o[x](a[0], a[1], a[2], a[3], a[4], a[5]);            break;        default:            alert('Too many arguments to apply.');        }        delete o[x];        return r;    });} if (!isFunction(Array.prototype.pop)) {    Array.method('pop', function () {        return this.splice(this.length - 1, 1)[0];    });}if (!isFunction(Array.prototype.push)) {    Array.method('push', function () {        this.splice.apply(this,            [this.length, 0].concat(Array.prototype.slice.apply(arguments)));        return this.length;    });}if (!isFunction(Array.prototype.shift)) {    Array.method('shift', function () {        return this.splice(0, 1)[0];    });}if (!isFunction(Array.prototype.splice)) {    Array.method('splice', function (s, d) {        var max = Math.max,            min = Math.min,            a = [], // The return value array            e,  // element            i = max(arguments.length - 2, 0),   // insert count            k = 0,            l = this.length,            n,  // new length            v,  // delta            x;  // shift count

        s = s || 0;        if (s < 0) {            s += l;        }        s = max(min(s, l), 0);  // start point        d = max(min(isNumber(d) ? d : l, l - s), 0);    // delete count        v = i - d;        n = l + v;        while (k < d) {            e = this[s + k];            if (!isUndefined(e)) {                a[k] = e;            }            k += 1;        }        x = l - s - d;        if (v < 0) {            k = s + i;            while (x) {                this[k] = this[k - v];                k += 1;                x -= 1;            }            this.length = n;        } else if (v > 0) {            k = 1;            while (x) {                this[n - k] = this[l - k];                k += 1;                x -= 1;            }        }        for (k = 0; k < i; ++k) {            this[s + k] = arguments[k + 2];        }        return a;    });}if (!isFunction(Array.prototype.unshift)) {    Array.method('unshift', function () {        this.splice.apply(this,            [0, 0].concat(Array.prototype.slice.apply(arguments)));        return this.length;    });}

原创粉丝点击