Object.keys() . Object.assign()

1.來不及了,直接看代碼吧

補充一點:
Object.keys 只收集自身屬性名,不收集繼承自原型鏈上的
Object.keys(obj),返回一個數(shù)組,數(shù)組里是該obj可被枚舉的所有屬性,以數(shù)組的形式返回。請看示例:

示例1

    function Pasta(grain, width, shape) {
            this.grain = grain;
            this.width = width;
            this.shape = shape;
            this.toString = function () {
                    return (this.grain + ", " + this.width + ", " + this.shape);
            }
    }

    console.log(Object.keys(Pasta)); //console: []
    var spaghetti = new Pasta("wheat", 0.2, "circle");
    console.log(Object.keys(spaghetti)); //console: ["grain", "width", "shape", "toString"]

console.log(Object.keys(Pasta)); //console: []
//解釋,由于沒有將構(gòu)造函數(shù)實例化,所以只打印了一個空數(shù)組
實例化之后,就將構(gòu)造函數(shù)所有的屬性都作為一個數(shù)組進行返回

實例二

    var arr = ["a", "b", "c"];
    console.log(Object.keys(arr)); // console: ["0", "1", "2"]

    var obj = { 0 : "a", 1 : "b", 2 : "c"};
    console.log(Object.keys(obj)); // console: ["0", "1", "2"]


    var an_obj = { 100: "a", 2: "b", 7: "c"};
    console.log(Object.keys(an_obj)); // console: ["2", "7", "100"]


    var my_obj = Object.create({}, { getFoo : { value : function () { return this.foo } } });
    my_obj.foo = 1;

    console.log(Object.keys(my_obj)); // console: ["foo"]

當傳入的是數(shù)組時候,返回的是數(shù)組的下標
是傳入對象,則返回對應(yīng)的屬性

Object.assign

自己實現(xiàn)一個

if(typeof Object.assign != function){
  Object.defineProperty(Object, 'assign', {
    value: function(target, varArgs){
      if(type target != null){
        let to = Object(target);
        for(var i=0; i< arguments.length; i++ ){
          nextSource = arguments[index]
          if(nextSource != null){
             for (let nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
           }
          }
        }
       return to
      }
    },
    writeable: true,
    configurable: true
  })
}



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容