Risposte:
È possibile eseguire il loop delle proprietà dell'oggetto come segue:
for(var prop in ad) {
if (ad.hasOwnProperty(prop)) {
// handle prop as required
}
}
È importante utilizzare il hasOwnProperty()metodo per determinare se l'oggetto ha la proprietà specificata come proprietà diretta e non ereditata dalla catena di prototipi dell'oggetto.
Dai commenti: puoi inserire quel codice in una funzione e farlo restituire false non appena raggiunge la parte in cui è presente il commento
Test della prestazione
Test di Object.Keys vs For..In Durante il test di qualsiasi proprietà
Object.keyssia il più semplice: var a = [1,2,3];a.something=4;console.log(Object.keys(a))poiché fa già parte di ECMA 5, puoi tranquillamente evitarlo: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Object.defineProperty(obj, 'foo', {enumerable:false, value:'foo'}).
È possibile utilizzare il Object.keysmetodo integrato per ottenere un elenco di chiavi su un oggetto e testarne la lunghezza.
var x = {};
// some code where value of x changes and than you want to check whether it is null or some object with values
if(Object.keys(x).length > 0){
// Your code here if x has some properties
}
var str = "MyString"; Object.keys(str); , la console emette 8 tasti, da 0 a 7, per ciascun personaggio. O ancora non capisco la risposta.
Che ne dici di fare una semplice funzione?
function isEmptyObject(obj) {
for(var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true;
}
isEmptyObject({}); // true
isEmptyObject({foo:'bar'}); // false
Il hasOwnProperty chiamata del metodo direttamente su Object.prototypeè solo per aggiungere un po 'più di sicurezza , immagina quanto segue usando una obj.hasOwnProperty(...)chiamata normale :
isEmptyObject({hasOwnProperty:'boom'}); // false
Nota: (per il futuro) Il metodo sopra riportato si basa for...insull'istruzione e questa istruzione scorre solo su proprietà enumerabili , nello standard ECMAScript attualmente implementato più ampiamente (3a edizione) il programmatore non ha alcun modo per creare proprietà non enumerabili .
Tuttavia, questo è cambiato ora con ECMAScript 5th Edition e siamo in grado di creare proprietà non enumerabili, non scrivibili o non cancellabili, quindi il metodo sopra può fallire , ad esempio:
var obj = {};
Object.defineProperty(obj, 'test', { value: 'testVal',
enumerable: false,
writable: true,
configurable: true
});
isEmptyObject(obj); // true, wrong!!
obj.hasOwnProperty('test'); // true, the property exist!!
Una soluzione ECMAScript 5 a questo problema sarebbe:
function isEmptyObject(obj) {
return Object.getOwnPropertyNames(obj).length === 0;
}
Il Object.getOwnPropertyNamesmetodo restituisce un Arraycontenente i nomi di tutti le proprietà di un oggetto, enumerabili o meno , questo metodo è ora implementato dai fornitori di browser, è già su Chrome 5 Beta e l'ultimo WebKit Nightly Builds.
Object.defineProperty è disponibile anche su quei browser e le ultime versioni Alpha di Firefox 3.7.
hasOwnPropertyproprietà, la funzione potrebbe bloccarsi ... So di essere un po 'paranoico ... ma a volte non sai in quale tipo di ambiente verrà utilizzato il tuo codice, ma sai quale metodo vuoi usare ...
Object.prototype, non viene enumerata da for...in. Quindi isEmptyObject({toString:1})fallirà. Questo è uno dei motivi per cui non si può sfortunati abbastanza utilizzare Objectcome una mappatura general-purpose.
Con jQuery puoi usare:
$.isEmptyObject(obj); // Returns: Boolean
A partire da jQuery 1.4 questo metodo controlla sia le proprietà sull'oggetto stesso sia le proprietà ereditate dai prototipi (in quanto non utilizza hasOwnProperty).
Con ECMAScript 5th Edition nei browser moderni (IE9 +, FF4 +, Chrome5 +, Opera12 +, Safari5 +) puoi utilizzare il metodo Object.keys integrato :
var obj = { blah: 1 };
var isEmpty = !Object.keys(obj).length;
O semplicemente vecchio JavaScript:
var isEmpty = function(obj) {
for(var p in obj){
return false;
}
return true;
};
I browser più recenti (e node.js) supportano Object.keys () che restituisce un array con tutte le chiavi letterali dell'oggetto in modo da poter eseguire le seguenti operazioni:
var ad = {};
Object.keys(ad).length;//this will be 0 in this case
Supporto browser: Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Se stai usando underscore.js, puoi usare la funzione _.isEmpty :
var obj = {};
var emptyObject = _.isEmpty(obj);
_.isEmpty([]) // true Assicurati di controllare prima: stackoverflow.com/a/22482737/1922747
Se si desidera utilizzare lodash , è possibile utilizzare il somemetodo.
_.some(obj) // returns true or false
Vedi questo piccolo esempio di jsbin
_.some([1, 2]) // true Assicurati di controllare prima: stackoverflow.com/a/13356338/1922747
for (var hasProperties in ad) break;
if (hasProperties)
... // ad has properties
Se devi essere sicuro e verificare la presenza di prototipi di oggetti (questi vengono aggiunti da determinate librerie e non presenti per impostazione predefinita):
var hasProperties = false;
for (var x in ad) {
if (ad.hasOwnProperty(x)) {
hasProperties = true;
break;
}
}
if (hasProperties)
... // ad has properties
for(var memberName in ad)
{
//Member Name: memberName
//Member Value: ad[memberName]
}
Membro significa proprietà Membro, variabile membro, come si desidera chiamarla> _>
Il codice sopra restituirà TUTTO, incluso toString ... Se vuoi solo vedere se il prototipo dell'oggetto è stato esteso:
var dummyObj = {};
for(var memberName in ad)
{
if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
//Member Name: memberName
//Member Value: ad[memberName]
}
Nota A: controlliamo se il membro dell'oggetto fittizio ha lo stesso tipo del membro dell'oggetto di test. Se si tratta di un'estensione, il tipo di membro dummyobject deve essere "non definito"
var hasAnyProps = false; for (var key in obj) { hasAnyProps = true; break; }
// as of this line hasAnyProps will show Boolean whether or not any iterable props exist
Semplice, funziona in tutti i browser e anche se tecnicamente è un ciclo per tutte le chiavi dell'oggetto NON passa in ciclo tutti ... o c'è 0 e il ciclo non viene eseguito o ce n'è uno e si interrompe dopo il primo uno (perché tutto ciò che stiamo controllando è se c'è QUALSIASI ... quindi perché continuare?)
Quando si è certi che l'oggetto sia definito dall'utente, il modo più semplice per determinare se UDO è vuoto sarebbe il seguente codice:
isEmpty=
/*b.b Troy III p.a.e*/
function(x,p){for(p in x)return!1;return!0};
Anche se questo metodo è (per natura) deduttivo, è il più veloce e il più veloce possibile.
a={};
isEmpty(a) >> true
a.b=1
isEmpty(a) >> false
ps:! non usarlo su oggetti definiti dal browser.
È possibile utilizzare quanto segue:
Doppio botto !! ricerca di proprietà
var a = !![]; // true
var a = !!null; // false
hasOwnProperty Questo è qualcosa che ho usato per usare:
var myObject = {
name: 'John',
address: null
};
if (myObject.hasOwnProperty('address')) { // true
// do something if it exists.
}
Tuttavia, JavaScript ha deciso di non proteggere il nome del metodo, quindi potrebbe essere manomesso.
var myObject = {
hasOwnProperty: 'I will populate it myself!'
};
prop in myObject
var myObject = {
name: 'John',
address: null,
developer: false
};
'developer' in myObject; // true, remember it's looking for exists, not value.
tipo di
if (typeof myObject.name !== 'undefined') {
// do something
}
Tuttavia, non controlla null.
Penso che questo sia il modo migliore.
in operatore
var myObject = {
name: 'John',
address: null
};
if('name' in myObject) {
console.log("Name exists in myObject");
}else{
console.log("Name does not exist in myObject");
}
risultato:
Il nome esiste in myObject
Ecco un collegamento che approfondisce l'operatore in: Determinare se esiste una proprietà oggetto
Funzione ES6
/**
* Returns true if an object is empty.
* @param {*} obj the object to test
* @return {boolean} returns true if object is empty, otherwise returns false
*/
const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0
Esempi:
let obj = "this is an object with String constructor"
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = {}
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = []
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = [{prop:"value"}]
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = {prop:"value"}
console.log(pureObjectIsEmpty(obj)) // empty? false
Cosa ne pensi di questo?
var obj = {},
var isEmpty = !obj;
var hasContent = !!obj