9

私たち Mootooler と Prototyper (このサイトにはほとんどいません) は通常、私たちが作成した (または借用した) 関数の便利なツールボックスを持ち歩いており、ネイティブ JavaScript オブジェクトに実装して、生活を少し楽にしています。非常に有用なプロトタイプ関数のリストをまとめたいと思いましたが、ネイティブ オブジェクト (つまりString.implement({...mootools) に実装されているものだけです。

それで、あなたのお気に入りは何ですか?


PS: 1 つのライブラリ用に作成された関数を別のライブラリに簡単に移植できるため、mootools とプロトタイプの両方を含めました。

PPS: ネイティブ JavaScript オブジェクトのプロトタイピングに対する賛成/反対の議論は知っていますが、ここでの議論は避けたいと思います。

4

5 に答える 5

2

私は tj111 が始めたことを続けました。ここに私の小さな追加があります:

Array.implement({
    //calculate the sum of all integers
    sum: function() {
        var sum = this.reduce(function(a, b) {
            return a + b;
        });
        return sum;
    }
});
于 2011-05-31T18:29:36.343 に答える
1

ネイティブプロパティの上書きを避けるために、作成前にプロパティをチェックする方法が好きです。

if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(){ ... };
}
于 2009-07-30T15:09:47.463 に答える
1

mootools のお気に入りをいくつか紹介します。

文字列関数

String.implement({

    //easy way to test if a string contains characters (input.value.isEmpty())
    isEmpty : function() {
        return (!this.test(/\w+/));
    },

    //add ellipses if string length > len
    ellipse : function(len) {
        return (this.length > len) ? this.substr(0, len) + "..." : this;
    },

    //finds all indexOf occurrences
    indexesOf : function(val) {
        var from = 0;
        var indexes = [];
        while (0 <= from && from < this.length) {
            var idx = this.indexOf(val, from);
            if (idx >= 0) {
                indexes.push(idx);
            } else {
                break;
            }
            from = idx+1;
        }
        return indexes;
    }
});

配列関数

Array.implement({

    //compare two arrays to see if they are identical
    compare : function(arr, strict) {
        strict = strict || false;
        if (this.length != arr.length)          return false;

        for (var i = 0; i < this.length; i++) {
            if ($type(this[i]) == "array") {
                if (!this[i].compare(arr[i]))   return false;
            }
            if (strict) {
                if (this[i] !== arr[i])     return false;
            } else {
                if (this[i] != arr[i])      return false;
            }
        }
        return true;
    },

    //remove non-unique array values
    unique : function() {
        for(var i = 0; i< this.length; i++) {
            var keys = this.indexesOf(this[i]);
            while (keys.length > 1) {
                this.splice(keys.pop(), 1);
            }
        }
        return this;
    },

    //same as array.unshift, except returns array instead of count
    //good for using inline... array.lpush('value').doSomethingElse()
    lpush : function() {
        for (var i = arguments.length -1 ; i >= 0; i--){
            this.unshift(arguments[i]);
        }
        return this;
    },

    //get all indexes of an item in an array
    indexesOf : function(item) {
        var ret = [];
        for (var i = 0; i < this.length; i++) {
            if (this[i] == item)    ret.push(i);
        }
        return ret;
    }
});
于 2009-07-14T19:24:17.593 に答える
1
//taken from http://prototype.lighthouseapp.com/projects/8886/tickets/351-new-swap-method-for-elements
Element.addMethods({
  swap: (function() {
    if ('swapNode' in document.documentElement)
      return function(element, other) {
        return $(element).swapNode($(other));
      };
    return function(element, other) {
       element = $(element);
       other = $(other);
       var next = other.nextSibling, parent = other.parentNode;
       element.parentNode.replaceChild(other, element);
       return parent.insertBefore(element, next);
    };
  })()
 });


// extend the array object to support indexed insertions
// submitted at http://prototype.lighthouseapp.com/projects/8886-prototype/tickets/356-arrayinsert
Array.prototype.insert=function(element,where) {
    var slice1=this.slice(0,where);
    var slice2=this.slice(where);

    return new Array.concat(slice1,element,slice2);
};


//extend the array object to support searching thrtough indexed arrays
// if returnIndex is true, then return the keyName, else return the value from that cell
Array.prototype.nextValue=function(startIndex,returnIndex) {
    for(var i=startIndex+1;i<this.length;i++){
        if(this[i]){
            return (returnIndex?i:this[i]);
        }
    }
    return null;
};


//extend the array object to support searching thrtough indexed arrays
// if returnIndex is true, then return the keyName, else return the value from that cell
Array.prototype.prevValue=function(startIndex,returnIndex) {
    for(var i=startIndex-1;i>=0;i--){
        if(this[i]){
            return (returnIndex?i:this[i]);
        }
    }
    return null;
};
于 2009-07-16T12:58:14.863 に答える
1

Prototype も Mootools も実際には開発していませんが、これらのフレームワークでも次のことが役立つと思います。

精度を指定するオプションの 2 番目のパラメーターを取るネイティブのMath.round()の置き換え:

Math.round(3.1415, 2); // 3.14

関数が否定された述語を取得するためのnot()メソッド:

var even = function(x){ return x % 2 === 0; };
var odd = even.not();
even(2); // true
odd(2); // false

しかし、最も有用なものは、それが安全な方法である場合に Object.prototype に追加するものです。代わりに、オブジェクトのプロパティを反復処理するグローバル関数をいくつか用意しています。

objMap()は Array.map() のように機能しますが、オブジェクト用です:

// returns {a:2, b:4, c:6}
objMap({a:1, b:2, c:3}, function(value) {
  return value*2;
});

objValues()およびobjKeys()を使用して、オブジェクトからプロパティ名または値の配列を取得します。

objValues({a:1, b:2, c:3}); // [1, 2, 3]
objKeys({a:1, b:2, c:3}); // ["a", "b", "c"]

そしてもちろんobjReduce()は、想像できるほとんどすべてのことを行います...

実装の詳細は、読者の演習として残しておきます :-)

于 2009-07-30T14:59:49.073 に答える