JS 物件的遍歷

Aguest發表於2024-07-21


定義一個物件,物件的鍵包含所有資料型別

const SymbolKey = Symbol('a')
const dict = {
  [66]: 66,
  "string": 'string',
  [true]: true,
  [undefined]: undefined,
  [null]: null,
  [BigInt(123)]: BigInt(123),
  [function () { console.log("hello") }]: 'function value',
  [{}]: 'object value',
  [[]]: 'array value',
  [SymbolKey]: 'symbol value',
  __proto__: Object.prototype,
}

使用常規迴圈迴圈方法

for (let key in dict) {
  console.log("key:", key, " value:", dict[key])
}

Object.keys(dict).forEach(key => {
  console.log("key:", key, " value:", dict[key])
});

Object.entries(dict).forEach(([key, value]) => {
  console.log("key:", key, " value:", value);
});

Object.getOwnPropertyNames(dict).forEach(key => {
  console.log("key:", key, " value:", dict[key])
});

列印結果:

key: 66  value: 66
key: 123  value: 123n
key: string  value: string
key: true  value: true
key: undefined  value: symbol value
key: null  value: null
key: function () { console.log("hello") }  value: function value
key: [object Object]  value: object value
key:   value: array value

可以看出除了物件的原型物件和Symbol其他資料型別都可以列印出來

// 獲取Symbol
const symbolKey = Object.getOwnPropertySymbols(dict)
console.log(symbolKey, dict[symbolKey[0]]);
// 獲取 __proto__
const protoKey = Object.getPrototypeOf(dict)
console.log(protoKey, dict.__proto__);

列印結果:

[ Symbol(a) ] symbol value
[Object: null prototype] {} [Object: null prototype] {}

遍歷物件全部屬性:

// 遍歷物件可列舉和不可列舉屬性

const getObjectKeys = (obj) => {
  let keys = Object.keys(obj)
  const symbolKeys = Object.getOwnPropertySymbols(dict)
  keys.push(...symbolKeys)
  const protoKey = Object.getPrototypeOf(dict)
  keys.push(protoKey)
  return keys
}
console.log(getObjectKeys(dict));

列印結果:

[
  '66',
  '123',
  'string',
  'true',
  'undefined',
  'null',
  'function () { console.log("hello") }',
  '[object Object]',
  '',
  Symbol(a),
  [Object: null prototype] {}
]

相關文章