Object物件常用方法總結

前端踩坑急救所發表於2018-11-16

【常用語法】
//1.定義物件: var const let
var Person = {
  name: `張三`,
  birth,//等同於birth: birth
  hello() { console.log(`我的名字是`, this.name); }// 等同於hello: function ()…
};

//2.物件的合併assign:

2.1.新增屬性*************************************
var target = { a: 1 };//合併成: {a:1, b:2, c:3},注:同名屬性,則後面的屬性會覆蓋前面的屬性。
var source1 = { b: 2 };
var source2 = { c: 3 };

Object.assign(target, source1, source2);

2.2.新增方法*********************************************
Object.assign(SomeClass.prototype, {
  someMethod(arg1, arg2) {
    ···
  },
  anotherMethod() {
    ···
  }
});
// 等同於下面的寫法
SomeClass.prototype.someMethod = function (arg1, arg2) {
···
};
SomeClass.prototype.anotherMethod = function () {
···
};

2.3.克隆物件********************************************
var obj1 = {a: {b: 1}};//obj1.a.b = 2;
var obj2 = Object.assign({}, obj1);//克隆物件obj1,得到:obj2.a.b=2

//只能克隆原始物件自身的值,不能克隆它繼承的值。
class Point {
  constructor(x, y) {
    Object.assign(this, {x, y});
  }
}
//解決方案
function clone(origin) {
  let originProto = Object.getPrototypeOf(origin);
  return Object.assign(Object.create(originProto), origin);
}

2.4.合併多個物件

const merge = (target, …sources) => Object.assign(target, …sources);
const merge = (…sources) => Object.assign({}, …sources);

2.5.為屬性指定預設值,即2.1的擴充套件
const DEFAULTS = {
  logLevel: 0,
  outputFormat: `html`
};

function processContent(options) {
  options = Object.assign({}, DEFAULTS, options);
  console.log(options);
  // …
}

【實踐操作:】

//1.獲取key value組合成陣列:js ES6
var obj = {
  ”name” : “zh”,
  ”age” : 22,
}
1.1.物件自身屬性遍歷
for(var key in obj){
  console.log(key); //鍵名
  console.log(obj[key]); //鍵值
  //if(obj.hasOwnProperty(key))

  if (obj.hasOwnProperty(key) === true) {
    console.log(obj[key])
  }

}

const  keys = Object.keys(obj);
const  values = Object.values(obj);

1.2.解構賦值
let { x, y, …z } = { x: 1, y: 2, a: 3, b: 4 };
x // 1
y // 2
z // { a: 3, b: 4 }

1.3.擴充套件運算子
let z = { a: 3, b: 4 };
let n = { …z };
n // { a: 3, b: 4 }

//2.取值判斷問題

2.1.讀取物件內部的某個屬性,往往需要判斷一下該物件是否存在
const firstName = message && message.body && message.body.user && message.body.user.firstName) || `default`;

if(firstName){

}
2.2.現在有一個提案,引入了“Null 傳導運算子”

const firstName = message?.body?.user?.firstName || `default`;

if(firstName){

}

相關文章