> 文章列表 > Object 对象的使用方法 --Javascript

Object 对象的使用方法 --Javascript

Object 对象的使用方法 --Javascript

Object 对象的使用方法 --Javascript

参考文章@小飞侠-2

1. Object.assign()

通过复制一个或多个对象来创建一个新的对象。
注意: 如果 源(source)对象中 有 目标对象(target)重复的属性,源对象中的属性会替换掉目标对象的相同属性。

let target = { a: 1, b: 2, c: 3 }
let source = { d: 4, e: 5 }let returnedResult = Object.assign(target,source)
console.log(returnedResult);
// { a: 1, b: 2, c: 3, d: 4, e: 5 }有重复属性时:
let target = { a: 1, b: 2, c: 3 }
let source = { c: 44, e: 55 }let returnedResult = Object.assign(target,source)
console.log(returnedResult);
// { a: 1, b: 2, c: 44, e: 55 }

2. Object.create()

使用指定的原型对象和属性创建一个新对象。

const person = {isHuman: false,printIntroduction: function () {console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);},
};const me = Object.create(person);me.name = "Matthew"; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwrittenme.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"

3. Object.defineProperties()

给对象添加一个属性并指定该属性的配置。

var obj = {};
Object.defineProperties(obj, {property1: {value: true,writable: true,},property2: {value: "Hello",writable: false,},// etc. etc.
});

4. Object.defineProperty()

直接在一个对象上定义一个新属性,或者修改一个对象的现有属性, 并返回这个对象。

5. Object.entries()

返回一个给定对象自身可枚举属性的键值对数组,其排列与使用 for…in 循环遍历该对象时返回的顺序一致(区别在于 for-in 循环也枚举原型链中的属性)
使用该方法后,会返回一个数组,(数组中还会包含两个数组)
数组中第一个元素是包含对象中所有的键的数组,
数组中第二个元素是包含对象中所有的值的数组

const object1 = { foo: "bar", baz: 42 };
console.log(Object.entries(object1)[1]);
// expected output: Array ["baz", 42]const object2 = { 0: "a", 1: "b", 2: "c" };
console.log(Object.entries(object2)[2]);
// expected output: Array ["2", "c"]const source = { name: "满山猴子我腚最红", age: 18 };
console.log(Object.entries(source));
//[ [ 'name', '满山猴子我腚最红' ], [ 'age', 18 ] ]const result = Object.entries(object2).sort((a, b) => a - b);
console.log(Object.entries(result)[1]);
// expected output: Array ["1", Array ["1", "b"]]

6. Object.freeze()

可以冻结一个对象。一个被冻结的对象再也不能被修改;冻结了一个对象则不能向这个对象添加新的属性,不能删除已有属性,不能修改该对象已有属性的可枚举性、可配置性、可写性,以及不能修改已有属性的值。此外,冻结一个对象后该对象的原型也不能被修改。freeze() 返回和传入的参数相同的对象。

const object1 = {property1: 42,
};const object2 = Object.freeze(object1);object2.property1 = 33;
// Throws an error in strict modeconsole.log(object2.property1);
// expected output: 42

7. Object.fromEntries()

把一个键值对列表 转换为一个对象。
一个数组就表示 一个键值对。

const arr = [["0", "a"],["1", "b"],["2", "c"],
];
const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }const object1 = { a: 1, b: 2, c: 3 };const object2 = Object.fromEntries(Object.entries(object1).map(([key, val]) => [key, val * 2])
);
console.log(object2);
// { a: 2, b: 4, c: 6 }
const sourceArr = [["name", "满山猴子我腚最红"],["age", 23],
];
const resultSourceArr = Object.fromEntries(sourceArr);
console.log(resultSourceArr);

8. Object.is()

判断两个值是否是相同的值

Object.is("foo", "foo"); // true
Object.is(window, window); // trueObject.is("foo", "bar"); // false
Object.is([], []); // falsevar foo = { a: 1 };
var bar = { a: 1 };
Object.is(foo, foo); // true
Object.is(foo, bar); // falseObject.is(null, null); // true// 特例
Object.is(0, -0); // false
Object.is(-0, -0); // true
Object.is(NaN, 0 / 0); // true

9. Object.isFrozen()

判断一个对象是否被冻结

// 使用Object.freeze是冻结一个对象最方便的方法.
var frozen = { 1: 81 };
Object.isFrozen(frozen) //=== false
Object.freeze(frozen);
Object.isFrozen(frozen) //=== true// 一个冻结对象也是一个密封对象.
Object.isSealed(frozen) //=== true// 当然,更是一个不可扩展的对象.
Object.isExtensible(frozen) //=== falseES5 中,如果参数不是一个对象类型,将抛出一个TypeError异常。在 ES2015 中,非对象参数将被视为一个冻结的普通对象,因此会返回true。Object.isFrozen(1);
// TypeError: 1 is not an object (ES5 code)Object.isFrozen(1);
// true                          (ES2015 code)

10. Object.keys()

返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用 for…in 循环遍历该对象时返回的顺序一致 。

let arr = ["one", "two", "three", "four", "five"];
console.log(Object.keys(arr)); //[ '0', '1', '2', '3', '4' ]let obj = {name: "满山猴子我腚最红",age: 18,sex: "male",
};
console.log(Object.keys(obj)); //[ 'name', 'age', 'sex' ]for (key in obj) {console.log(key, "forin");
}

11. Object.values()

返回一个给定对象自身的所有可枚举属性值的数组,值的顺序与使用 for…in 循环的顺序相同 ( 区别在于 for-in 循环枚举原型链中的属性 )。

let arr = ["one", "two", "three", "four", "five"];
console.log(Object.values(arr)); //[ 'one', 'two', 'three', 'four', 'five' ]let obj = {name: "满山猴子我腚最红",age: 18,sex: "male",
};
console.log(Object.values(obj)); //[ '满山猴子我腚最红', 18, 'male' ]for (key in obj) {console.log(obj[key]);
}

12. Object.hasOwnProperty(arg)

判断一个对象中是否包含某个属性。返回值是一个 布尔值。
注意:只会判断 当前对象是否包含某属性,不能判断该对象的原型上是否包含某属性。

let sourceObject = {name: "满山猴子我腚最红",age: 18,sex: "male",
};
console.log(sourceObject.hasOwnProperty("name")); // true
console.log(sourceObject.hasOwnProperty("address")); // false// 判断 source 对象中是否包含 name 属性。
let person = {name: "coco",address: "宁波市慈溪市杭州湾",production: function () {return `1111`;},
};
let source = Object.create(person);console.log(source.name); // coco
console.log(source.hasOwnProperty("name")); // false

13. Object.prototype.toString.call(obj)

判断当前对象的数据类型

console.log(Object.prototype.toString.call("jerry")); //[object String]
console.log(Object.prototype.toString.call(12)); //[object Number]
console.log(Object.prototype.toString.call(true)); //[object Boolean]
console.log(Object.prototype.toString.call(undefined)); //[object Undefined]
console.log(Object.prototype.toString.call(null)); //[object Null]
console.log(Object.prototype.toString.call({ name: "jerry" })); //[object Object]
console.log(Object.prototype.toString.call(function () {})); //[object Function]
console.log(Object.prototype.toString.call([])); //[object Array]
console.log(Object.prototype.toString.call(new Date())); //[object Date]
console.log(Object.prototype.toString.call(/\\d/)); //[object RegExp]function Person() {}
console.log(Object.prototype.toString.call(new Person())); //[object Object]

封装 Object.prototype.toString.call() 工具

参考文章@前端小石头

function classof(o) {if (o === null) return "null";if (typeof o !== "object") return typeof o;elsereturn Object.prototype.toString.call(o).slice(8, -1).toLocaleLowerCase();
}classof(2020); // number
classof("石头加油"); // string
classof(true); // boolean
classof(undefined); // undefined
classof(null); // null
classof(Symbol("没毛病!")); // symbol
classof(1n); // bigint
classof({}); // object
classof(classof); // function
classof([]); // array
classof(new Date()); // date
// 还是没法细分自定义类,如果需要的话可以再结合constructor.name继续封装
classof(new classof()); // object