這篇文章主要介紹“JS中Object對象的用法”,在日常操作中,相信很多人在JS中Object對象的用法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”JS中Object對象的用法”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
方法用于將所有可枚舉屬性的值從一個或多個源對象復制到目標對象。它將返回目標對象。
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 }方法創建一個新對象,使用現有的對象來提供新創建的對象的proto。
const person = {
color: "red",
sayName: function () {
console.log(this.name);
},
};
const m = Object.create(person);
m.name = "chuchur";
m.sayName(); // chuchur方法直接在一個對象上定義新的屬性或修改現有屬性,并返回該對象。
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"}方法會直接在一個對象上定義一個新屬性,或者修改一個對象的現有屬性,并返回這個對象。
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方法返回一個給定對象自身可枚舉屬性的鍵值對數組,其排列與使用for...in循環遍歷該對象時返回的順序一致(區別在于for-in循環也枚舉原型鏈中的屬性)。
const obj = { foo: "bar", baz: 42 };
console.log(Object.entries(obj));
//[['foo','bar'],['baz',42]]方法會返回一個由一個給定對象的自身可枚舉屬性組成的數組,數組中屬性名的排列順序和使用for...in循環遍歷該對象時返回的順序一致 。
// simple array
var arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// array like object
var obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// array like object with random key ordering
var anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']
// getFoo is a property which isn't enumerable
var myObj = Object.create(
{},
{
getFoo: {
value: function () {
return this.foo;
},
},
}
);
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']方法返回一個給定對象自己的所有可枚舉屬性值的數組,值的順序與使用for...in循環的順序相同(區別在于for-in循環枚舉原型鏈中的屬性 )。
var obj = { foo: "bar", baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]
// array like object
var 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 keys
var an_obj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.values(an_obj)); // ['b', 'c', 'a']
// getFoo is property which isn't enumerable
var 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 object
console.log(Object.values("foo")); // ['f', 'o', 'o'] ==Array.from('foo')
//ES5
if (!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;
};方法會返回一個布爾值,指示對象自身屬性中是否具有指定的屬性。
o = new Object();
o.prop = "exists";
function changeO() {
o.newprop = o.prop;
delete o.prop;
}
o.hasOwnProperty("prop"); // 返回 true
changeO();
o.hasOwnProperty("prop"); // 返回 false
o.hasOwnProperty("toString"); // 返回 false
o.hasOwnProperty("hasOwnProperty"); // 返回 false方法返回指定對象上一個自有屬性對應的屬性描述符。(自有屬性指的是直接賦予該對象的屬性,不需要從原型鏈上進行查找的屬性)
o = { bar: 42 };
d = Object.getOwnPropertyDescriptor(o, "bar");
// d {
// configurable: true,
// enumerable: true,
// value: 42,
// writable: true
// }方法用來獲取一個對象的所有自身屬性的描述符。
Object.assign()方法只能拷貝源對象的可枚舉的自身屬性,同時拷貝時無法拷貝屬性的特性們,而且訪問器屬性會被轉換成數據屬性,也無法拷貝源對象的原型,該方法配合Object.create() 方法可以實現上面說的這些。
Object.create( Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj) );
方法返回一個由指定對象的所有自身屬性的屬性名(包括不可枚舉屬性但不包括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"]方法返回一個給定對象自身的所有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); // 2
console.log(objectSymbols); // [Symbol(a), Symbol(b)]
console.log(objectSymbols[0]); // Symbol(a)方法用于測試一個對象是否存在于另一個對象的原型鏈上。
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)); // true
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true方法返回一個布爾值,表示指定的屬性是否可枚舉。
var o = {};
var a = [];
o.prop = "is enumerable";
a[0] = "is enumerable";
o.propertyIsEnumerable("prop"); // 返回 true
a.propertyIsEnumerable(0); // 返回 true
//用戶自定義對象和引擎內置對象
var a = ["is enumerable"];
a.propertyIsEnumerable(0); // 返回 true
a.propertyIsEnumerable("length"); // 返回 false
Math.propertyIsEnumerable("random"); // 返回 false
this.propertyIsEnumerable("Math"); // 返回 false
//自身屬性和繼承屬性
var a = [];
a.propertyIsEnumerable("constructor"); // 返回 false
function 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"); // 返回 true
o.propertyIsEnumerable("method"); // 返回 true
o.propertyIsEnumerable("property"); // 返回 false
o.property = "is enumerable";
o.propertyIsEnumerable("property"); // 返回 true
// 這些返回fasle,是因為,在原型鏈上propertyIsEnumerable不被考慮
// (盡管最后兩個在for-in循環中可以被循環出來)。
o.propertyIsEnumerable("prototype"); // 返回 false (根據 JS 1.8.1/FF3.6)
o.propertyIsEnumerable("constructor"); // 返回 false
o.propertyIsEnumerable("firstMethod"); // 返回 false方法返回指定對象的原型(內部[[Prototype]])屬性的
const prototype1 = {};
const object1 = Object.create(prototype1);
console.log(Object.getPrototypeOf(object1) === prototype1);
// expected output: true方法判斷兩個值是否是相同的值。
Object.is("foo", "foo"); // true
Object.is(window, window); // true
Object.is("foo", "bar"); // false
Object.is([], []); // false
var test = { a: 1 };
Object.is(test, test); // true
Object.is(null, null); // true
// 特例
Object.is(0, -0); // false
Object.is(-0, -0); // true
Object.is(NaN, 0 / 0); // true
// ES5
if (!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將原對象變的不可擴展,并且返回原對象.
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異常方法判斷一個對象是否是可擴展的(是否可以在它上面添加新的屬性)。
// 新對象默認是可擴展的.
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方法可以凍結一個對象,凍結指的是不能向這個對象添加新的屬性,不能修改其已有屬性的值,不能刪除已有屬性,以及不能修改該對象已有屬性的可枚舉性、可配置性、可寫性。該方法返回被凍結的對象。
const object1 = {
property1: 42,
};
const object2 = Object.freeze(object1);
object2.property1 = 33;
// 嚴格模式會報錯,非嚴格模式不報錯,但是不執行
console.log(object2.property1);
// 輸出: 42方法判斷一個對象是否被凍結。
// 使用Object.freeze是凍結一個對象最方便的方法.
var frozen = { 1: 81 };
Object.isFrozen(frozen); //=== false
Object.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方法封閉一個對象,阻止添加新屬性并將所有現有屬性標記為不可配置。當前屬性的值只要可寫就可以改變。
const object1 = {
property1: 42,
};
Object.seal(object1);
object1.property1 = 33;
console.log(object1.property1);
// expected output: 33
delete object1.property1; // cannot delete when sealed
console.log(object1.property1);
// expected output: 33方法判斷一個對象是否被密封。
// 新建的對象默認不是密封的.
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 ,訪問器屬性不考慮可寫不可寫,只考慮是否可配置方法返回指定對象的原始值。
// 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或false
var 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); // true
var 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到此,關于“JS中Object對象的用法”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。