javascript中object一些高效的操作方法
object.assign()方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
const object1 = { a: 1, b: 2, c: 3 };const object2 = object.assign({ c: 4, d: 5 }, object1);console.log(object2); // { a: 1, b: 2, c: 3 ,c: 4, d: 5 }
object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的proto。
const person = { color: "red", sayname: function () { console.log(this.name); },};const m = object.create(person);m.name = "chuchur";m.sayname(); // chuchur
object.defineproperties()方法直接在一个对象上定义新的属性或修改现有属性,并返回该对象。
var obj = {};object.defineproperties(obj, { property1: { value: 1, writable: true, }, property2: { value: "hello", writable: false, },});obj.property1 = 1;obj.property2 = 2;console.log(obj); // {property1: 1, property2: "hello"}
object.defineproperty()方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回这个对象。
var o = {}; // 创建一个新对象// 在对象中添加一个属性与数据描述符的示例object.defineproperty(o, "a", { value: 37, writable: true, enumerable: true, configurable: true,});// 对象o拥有了属性a,值为37// 在对象中添加一个属性与存取描述符的示例var bvalue;object.defineproperty(o, "b", { get: function () { return bvalue; }, set: function (newvalue) { bvalue = newvalue; }, enumerable: true, configurable: true,});o.b = 38;// 对象o拥有了属性b,值为38// o.b的值现在总是与bvalue相同,除非重新定义o.b
object.entries()方法返回一个给定对象自身可枚举属性的键值对数组,其排列与使用for...in循环遍历该对象时返回的顺序一致(区别在于for-in循环也枚举原型链中的属性)。
const obj = { foo: "bar", baz: 42 };console.log(object.entries(obj));//[['foo','bar'],['baz',42]]
object.keys()方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用for...in循环遍历该对象时返回的顺序一致 。
// simple arrayvar arr = ["a", "b", "c"];console.log(object.keys(arr)); // console: ['0', '1', '2']// array like objectvar obj = { 0: "a", 1: "b", 2: "c" };console.log(object.keys(obj)); // console: ['0', '1', '2']// array like object with random key orderingvar anobj = { 100: "a", 2: "b", 7: "c" };console.log(object.keys(anobj)); // console: ['2', '7', '100']// getfoo is a property which isn't enumerablevar myobj = object.create( {}, { getfoo: { value: function () { return this.foo; }, }, });myobj.foo = 1;console.log(object.keys(myobj)); // console: ['foo']
object.values()方法返回一个给定对象自己的所有可枚举属性值的数组,值的顺序与使用for...in循环的顺序相同(区别在于for-in循环枚举原型链中的属性 )。
var obj = { foo: "bar", baz: 42 };console.log(object.values(obj)); // ['bar', 42]// array like objectvar obj = { 0: "a", 1: "b", 2: "c" };console.log(object.values(obj)); // ['a', 'b', 'c']// array like object with random key ordering// when we use numeric keys, the value returned in a numerical order according to the keysvar an_obj = { 100: "a", 2: "b", 7: "c" };console.log(object.values(an_obj)); // ['b', 'c', 'a']// getfoo is property which isn't enumerablevar my_obj = object.create( {}, { getfoo: { value: function () { return this.foo; }, }, });my_obj.foo = "bar";console.log(object.values(my_obj)); // ['bar']// non-object argument will be coerced to an objectconsole.log(object.values("foo")); // ['f', 'o', 'o'] ==array.from('foo')//es5if (!object.values) object.values = function (obj) { if (obj !== object(obj)) throw new typeerror("object.values called on a non-object"); var val = [], key; for (key in obj) { if (object.prototype.hasownproperty.call(obj, key)) { val.push(obj[key]); } } return val; };
object.hasownproperty()方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性。
o = new object();o.prop = "exists";function changeo() { o.newprop = o.prop; delete o.prop;}o.hasownproperty("prop"); // 返回 truechangeo();o.hasownproperty("prop"); // 返回 falseo.hasownproperty("tostring"); // 返回 falseo.hasownproperty("hasownproperty"); // 返回 false
object.getownpropertydescriptor()方法返回指定对象上一个自有属性对应的属性描述符。(自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性)
o = { bar: 42 };d = object.getownpropertydescriptor(o, "bar");// d {// configurable: true,// enumerable: true,// value: 42,// writable: true// }
object.getownpropertydescriptors()方法用来获取一个对象的所有自身属性的描述符。
object.assign()方法只能拷贝源对象的可枚举的自身属性,同时拷贝时无法拷贝属性的特性们,而且访问器属性会被转换成数据属性,也无法拷贝源对象的原型,该方法配合object.create() 方法可以实现上面说的这些。
object.create( object.getprototypeof(obj), object.getownpropertydescriptors(obj));
object.getownpropertynames()方法返回一个由指定对象的所有自身属性的属性名(包括不可枚举属性但不包括symbol值作为名称的属性)组成的数组。
var arr = ["a", "b", "c"];console.log(object.getownpropertynames(arr).sort()); // ["0", "1", "2", "length"]// 类数组对象var obj = { 0: "a", 1: "b", 2: "c" };console.log(object.getownpropertynames(obj).sort()); // ["0", "1", "2"]// 使用array.foreach输出属性名和属性值object.getownpropertynames(obj).foreach(function (val, idx, array) { console.log(val + " -> " + obj[val]);});// 输出// 0 -> a// 1 -> b// 2 -> c//不可枚举属性var my_obj = object.create( {}, { getfoo: { value: function () { return this.foo; }, enumerable: false, }, });my_obj.foo = 1;console.log(object.getownpropertynames(my_obj).sort()); // ["foo", "getfoo"]
object.getownpropertysymbols()方法返回一个给定对象自身的所有symbol属性的数组。
var obj = {};var a = symbol("a");var b = symbol.for("b");obj[a] = "localsymbol";obj[b] = "globalsymbol";var objectsymbols = object.getownpropertysymbols(obj);console.log(objectsymbols.length); // 2console.log(objectsymbols); // [symbol(a), symbol(b)]console.log(objectsymbols[0]); // symbol(a)
object.isprototypeof()方法用于测试一个对象是否存在于另一个对象的原型链上。
function foo() {}function bar() {}function baz() {}bar.prototype = object.create(foo.prototype);baz.prototype = object.create(bar.prototype);var baz = new baz();console.log(baz.prototype.isprototypeof(baz)); // trueconsole.log(bar.prototype.isprototypeof(baz)); // trueconsole.log(foo.prototype.isprototypeof(baz)); // trueconsole.log(object.prototype.isprototypeof(baz)); // true
object.propertyisenumerable()方法返回一个布尔值,表示指定的属性是否可枚举。
var o = {};var a = [];o.prop = "is enumerable";a[0] = "is enumerable";o.propertyisenumerable("prop"); // 返回 truea.propertyisenumerable(0); // 返回 true//用户自定义对象和引擎内置对象var a = ["is enumerable"];a.propertyisenumerable(0); // 返回 truea.propertyisenumerable("length"); // 返回 falsemath.propertyisenumerable("random"); // 返回 falsethis.propertyisenumerable("math"); // 返回 false//自身属性和继承属性var a = [];a.propertyisenumerable("constructor"); // 返回 falsefunction firstconstructor() { this.property = "is not enumerable";}firstconstructor.prototype.firstmethod = function () {};function secondconstructor() { this.method = function method() { return "is enumerable"; };}secondconstructor.prototype = new firstconstructor();secondconstructor.prototype.constructor = secondconstructor;var o = new secondconstructor();o.arbitraryproperty = "is enumerable";o.propertyisenumerable("arbitraryproperty"); // 返回 trueo.propertyisenumerable("method"); // 返回 trueo.propertyisenumerable("property"); // 返回 falseo.property = "is enumerable";o.propertyisenumerable("property"); // 返回 true// 这些返回fasle,是因为,在原型链上propertyisenumerable不被考虑// (尽管最后两个在for-in循环中可以被循环出来)。o.propertyisenumerable("prototype"); // 返回 false (根据 js 1.8.1/ff3.6)o.propertyisenumerable("constructor"); // 返回 falseo.propertyisenumerable("firstmethod"); // 返回 false
object.getprototypeof()方法返回指定对象的原型(内部[[prototype]])属性的
const prototype1 = {};const object1 = object.create(prototype1);console.log(object.getprototypeof(object1) === prototype1);// expected output: true
object.is()方法判断两个值是否是相同的值。
object.is("foo", "foo"); // trueobject.is(window, window); // trueobject.is("foo", "bar"); // falseobject.is([], []); // falsevar test = { a: 1 };object.is(test, test); // trueobject.is(null, null); // true// 特例object.is(0, -0); // falseobject.is(-0, -0); // trueobject.is(nan, 0 / 0); // true// es5if (!object.is) { object.is = function (x, y) { // samevalue algorithm if (x === y) { // steps 1-5, 7-10 // steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // step 6.a: nan == nan return x !== x && y !== y; } };}
object.preventextensions()方法让一个对象变的不可扩展,也就是永远不能再添加新的属性。
// object.preventextensions将原对象变的不可扩展,并且返回原对象.var obj = {};var obj2 = object.preventextensions(obj);obj === obj2; // true// 字面量方式定义的对象默认是可扩展的.var empty = {};object.isextensible(empty); //=== true// ...但可以改变.object.preventextensions(empty);object.isextensible(empty); //=== false// 使用object.defineproperty方法为一个不可扩展的对象添加新属性会抛出异常.var nonextensible = { removable: true };object.preventextensions(nonextensible);object.defineproperty(nonextensible, "new", { value: 8675309 }); // 抛出typeerror异常// 在严格模式中,为一个不可扩展对象的新属性赋值会抛出typeerror异常.function fail() { "use strict"; nonextensible.newproperty = "fail"; // throws a typeerror}fail();// 一个不可扩展对象的原型是不可更改的,__proto__是个非标准魔法属性,可以更改一个对象的原型.var fixed = object.preventextensions({});fixed.__proto__ = { oh: "hai" }; // 抛出typeerror异常
object.isextensible()方法判断一个对象是否是可扩展的(是否可以在它上面添加新的属性)。
// 新对象默认是可扩展的.var empty = {};object.isextensible(empty); // === true// ...可以变的不可扩展.object.preventextensions(empty);object.isextensible(empty); // === false// 密封对象是不可扩展的.var sealed = object.seal({});object.isextensible(sealed); // === false// 冻结对象也是不可扩展.var frozen = object.freeze({});object.isextensible(frozen); // === false
object.freeze()方法可以冻结一个对象,冻结指的是不能向这个对象添加新的属性,不能修改其已有属性的值,不能删除已有属性,以及不能修改该对象已有属性的可枚举性、可配置性、可写性。该方法返回被冻结的对象。
const object1 = { property1: 42,};const object2 = object.freeze(object1);object2.property1 = 33;// 严格模式会报错,非严格模式不报错,但是不执行console.log(object2.property1);// 输出: 42
object.isfrozen()方法判断一个对象是否被冻结。
// 使用object.freeze是冻结一个对象最方便的方法.var frozen = { 1: 81 };object.isfrozen(frozen); //=== falseobject.freeze(frozen);object.isfrozen(frozen); //=== true// 一个冻结对象也是一个密封对象.object.issealed(frozen); //=== true// 当然,更是一个不可扩展的对象.object.isextensible(frozen); //=== false// 一个对象默认是可扩展的,所以它也是非冻结的.object.isfrozen({}); // === false// 一个不可扩展的空对象同时也是一个冻结对象.var vacuouslyfrozen = object.preventextensions({});object.isfrozen(vacuouslyfrozen); //=== true;// 一个非空对象默认也是非冻结的.var oneprop = { p: 42 };object.isfrozen(oneprop); //=== false// 让这个对象变的不可扩展,并不意味着这个对象变成了冻结对象,// 因为p属性仍然是可以配置的(而且可写的).object.preventextensions(oneprop);object.isfrozen(oneprop); //=== false// ...如果删除了这个属性,则它会成为一个冻结对象.delete oneprop.p;object.isfrozen(oneprop); //=== true// 一个不可扩展的对象,拥有一个不可写但可配置的属性,则它仍然是非冻结的.var nonwritable = { e: "plep" };object.preventextensions(nonwritable);object.defineproperty(nonwritable, "e", { writable: false }); // 变得不可写object.isfrozen(nonwritable); //=== false// 把这个属性改为不可配置,会让这个对象成为冻结对象.object.defineproperty(nonwritable, "e", { configurable: false }); // 变得不可配置object.isfrozen(nonwritable); //=== true// 一个不可扩展的对象,拥有一个不可配置但可写的属性,则它仍然是非冻结的.var nonconfigurable = { release: "the kraken!" };object.preventextensions(nonconfigurable);object.defineproperty(nonconfigurable, "release", { configurable: false });object.isfrozen(nonconfigurable); //=== false// 把这个属性改为不可写,会让这个对象成为冻结对象.object.defineproperty(nonconfigurable, "release", { writable: false });object.isfrozen(nonconfigurable); //=== true// 一个不可扩展的对象,值拥有一个访问器属性,则它仍然是非冻结的.var accessor = { get food() { return "yum"; },};object.preventextensions(accessor);object.isfrozen(accessor); //=== false// ...但把这个属性改为不可配置,会让这个对象成为冻结对象.object.defineproperty(accessor, "food", { configurable: false });object.isfrozen(accessor); //=== true
object.seal()方法封闭一个对象,阻止添加新属性并将所有现有属性标记为不可配置。当前属性的值只要可写就可以改变。
const object1 = { property1: 42,};object.seal(object1);object1.property1 = 33;console.log(object1.property1);// expected output: 33delete object1.property1; // cannot delete when sealedconsole.log(object1.property1);// expected output: 33
object.issealed()方法判断一个对象是否被密封。
// 新建的对象默认不是密封的.var empty = {};object.issealed(empty); // === false// 如果你把一个空对象变的不可扩展,则它同时也会变成个密封对象.object.preventextensions(empty);object.issealed(empty); // === true// 但如果这个对象不是空对象,则它不会变成密封对象,因为密封对象的所有自身属性必须是不可配置的.var hasprop = { fee: "fie foe fum" };object.preventextensions(hasprop);object.issealed(hasprop); // === false// 如果把这个属性变的不可配置,则这个对象也就成了密封对象.object.defineproperty(hasprop, "fee", { configurable: false });object.issealed(hasprop); // === true// 最简单的方法来生成一个密封对象,当然是使用object.seal.var sealed = {};object.seal(sealed);object.issealed(sealed); // === true// 一个密封对象同时也是不可扩展的.object.isextensible(sealed); // === false// 一个密封对象也可以是一个冻结对象,但不是必须的.object.isfrozen(sealed); // === true ,所有的属性都是不可写的var s2 = object.seal({ p: 3 });object.isfrozen(s2); // === false, 属性"p"可写var s3 = object.seal({ get p() { return 0; },});object.isfrozen(s3); // === true ,访问器属性不考虑可写不可写,只考虑是否可配置
object.valueof()方法返回指定对象的原始值。
// array:返回数组对象本身var array = ["abc", true, 12, -5];console.log(array.valueof() === array); // true// date:当前时间距1970年1月1日午夜的毫秒数var date = new date(2013, 7, 18, 23, 11, 59, 230);console.log(date.valueof()); // 1376838719230// number:返回数字值var num = 15.2654;console.log(num.valueof()); // 15.2654// 布尔:返回布尔值true或falsevar bool = true;console.log(bool.valueof() === bool); // true// new一个boolean对象var newbool = new boolean(true);// valueof()返回的是true,两者的值相等console.log(newbool.valueof() == newbool); // true// 但是不全等,两者类型不相等,前者是boolean类型,后者是object类型console.log(newbool.valueof() === newbool); // false// function:返回函数本身function foo() {}console.log(foo.valueof() === foo); // truevar foo2 = new function("x", "y", "return x + y;");console.log(foo2.valueof());/*ƒ anonymous(x,y) {return x + y;}*/// object:返回对象本身var obj = { name: "张三", age: 18 };console.log(obj.valueof() === obj); // true// string:返回字符串值var str = "http://www.xyz.com";console.log(str.valueof() === str); // true// new一个字符串对象var str2 = new string("http://www.xyz.com");// 两者的值相等,但不全等,因为类型不同,前者为string类型,后者为object类型console.log(str2.valueof() === str2); // false
推荐学习:javascript视频教程
以上就是一文讲解js中object对象一些操作方法(分享)的详细内容。
