Object構造器的參數若是爲空或null、undefined將返回一個空的Object對象,若是爲其餘值則調用相應的構造器,如javascript
new Object() // Object {} new Object(null) // Object {} new Object(undefined) // Object {} new Object(1) // Number {[[PrimitiveValue]]: 1} new Object("a") // String {0: "a", length: 1, [[PrimitiveValue]]: "a"} new Object({}) // Object {} new Object([1,2,3]) // [1, 2, 3] new Object(function(){}) // function (){}
若是傳遞多個參數取第一個,因爲使用構造器來建立對象須要判斷參數因此通常比咱們直接使用字面量{}建立對象要慢一些。html
咱們也能夠本身定義一個構造器來建立對象,以下java
function CreateObj(){} var obj = new CreateObj(); obj.a = 10; // 10
這些方法建立的對象都不是一個真正乾淨的對象,若是但願建立一個沒有原型繼承的空對象則可使用Object.create方法數組
Object.create(null) // Object {} No Properties
var obj = { title: '晴天', content: '....' };
key能夠以字符串形式來寫也能夠按標識符來寫,通常咱們會以標識符來寫,當遇到須要使用一些不合法的標識符時咱們會以字符串的形式來寫,如:prototype
{1:2}; {.l:1};
因爲以上對象屬性名是不合法的,所以咱們須要使用字符串的形式來寫。code
{'1':2}; {'.l':1};
若是key和value名同樣,value值能夠不寫htm
var a = 1; var obj = {a}; console.log(obj); // Object {a: 1}
若是但願key是一個變量,咱們能夠這樣對象
var a = 'hello'; console.log({[a]:a}); Object {hello: "hello"}
在一個對象中不能有多個同名屬性,若是相同最後一個將覆蓋以前的繼承
{ a:123, a:456 } // Object {a: 456}
對象不能有多個同名屬性的特性,咱們可使用它來實現數組過濾重複項ip
var arr = [1,3,3,2,1,1], obj = {}; arr.forEach((item)=>obj[item] = item); console.log(obj) // Object {1: 1, 2: 2, 3: 3}
但因爲對象的儲存並非按照咱們填寫的順序來的,所以對於有順序要求的咱們就不能使用上面的方式來實現了。
對象和數組在某些方面很是類似,所以只須要咱們按照數組的格式來寫就能夠將對象轉換成一個數組
Array.from({ '0':'hello', '1':'world', 'length':2 }) // ["hello", "world"]
for in
var obj = {html:111,javascript:222}; for(let key in obj){ console.log(obj[key]); } // 111 // 222
for in會將原型繼承中的值也循環出來,所以咱們須要過濾一下
// 沒過濾以前 Object.prototype.a = '搗亂的'; var obj = {html:111,javascript:222}; for(let key in obj){ console.log(obj[key]); } // 111 // 222 // 搗亂的 // 過濾以後 Object.prototype.a = '搗亂的'; var obj = {html:111,javascript:222}; for(let key in obj){ if(obj.hasOwnProperty(key)){ console.log(obj[key]); } } // 111 // 222
咱們也能夠用for來循環對象,不過咱們得先使用Object.keys來取對象的key
Object.prototype.a = '搗亂的'; var obj = {html:111,javascript:222}; var arr = Object.keys(obj); for(let i = 0; i < arr.length; i++){ console.log(obj[arr[i]]); } // 111 // 222
for of
Object.prototype.a = '搗亂的'; var obj = {html:111,javascript:222}; for(let key of Object.keys(obj)){ console.log(obj[key]); } // 111 // 222
和對象、function相加會轉換成字符串拼接,若是是其餘值則會轉換爲數字
{} + null // 0 {} + undefined // NaN {} + 'a' // NaN {} + '111' // 111 {} + {} // "[object Object][object Object]" {} + [2] // 2 {} + function(){} // "[object Object]function (){}"
若是是相減則會將對象轉換爲-0(注意是-0),若是是對象減對象則是NaN
{} - '' // -0 {} - [] // -0 {} - null // -0 {} - undefined // NaN {} - {} // NaN {} - function(){} // NaN {} - 2 // -2
爲何說對象被轉換成負0而不是0呢,咱們用一個例子來證實
0 - 0 // 0 -0 - 0 // -0
因此說對象被轉換成-0而不是0