2017-05-29 57 views

回答

0

通過使用arr.length = 0,可以使用for...in循環和空數組循環對象屬性。您也可以使用Array.isArray()來首先檢查值是否爲數組。

var myobj = { 
 
    location : [ 'item1', 'item2', 'item3' ], 
 
    job : [ 'job1', 'job2', 'job3' ], 
 
    other : [ 'other1', 'other2', 'other3' ] 
 
} 
 

 
for(var key in myobj) { 
 
    if(Array.isArray(myobj[key])) myobj[key].length = 0; 
 
} 
 
console.log(myobj)

或者你可以使用Object.keys()forEach()環代替。

var myobj = { 
 
    location : [ 'item1', 'item2', 'item3' ], 
 
    job : [ 'job1', 'job2', 'job3' ], 
 
    other : [ 'other1', 'other2', 'other3' ] 
 
} 
 

 
Object.keys(myobj).forEach(key => myobj[key].length = 0) 
 
console.log(myobj)

+0

@George Katsanos當然。 –

0

myobj = { 
 
    location: ['item1', 'item2', 'item3'], 
 
    job: ['job1', 'job2', 'job3'], 
 
    other: ['other1', 'other2', 'other3'] 
 
} 
 
var getAllKeys = Object.keys(myobj); 
 
getAllKeys.forEach(function(item) { 
 
    myobj[item].length = 0; 
 
}) 
 

 

 
console.log(myobj)

0
myobj = { 
    location : [ item1, item2, item3 ], 
    job : [ job1, job2, job3 ], 
    other : [ other1, other2, other3 ] 
} 

for(var key in myobj){ 
    myobj[key] = []; 
}