笔记:js对象遍历

JavaScript中的对象概念非常不同,要把它当作其它语言的关联数组(如PHP)或者Map(如Java)来理解的话,还是有很大的不一样——由于原型链属性描述符(主要是[[Enumerable]])的存在。

一个对象字面量{}Object作为原型,它有继承自原型链的不可枚举的toString方法。下面将以对象字面量为例。

  • 下标操作符、点操作符可以访问到自身属性或继承自原型链的任何属性,除非出现了属性覆盖
    var a ={}; a.toString返回toString方法
    var a ={toString:"a"}; a.toString返回字符串”a”

  • for in循环将枚举的自身属性和继承自原型链的所有[[Enumerable]]的属性

  • "key" in obj的判断中,判断自身属性或继承自原型链的属性的存在性
    "toString" in {}返回true

  • obj.hasOwnProperty()的判断中,只判断自身属性的存在性
    ({}).hasOwnProperty("toString")返回false
    ({toString:"a"}).hasOwnProperty("toString")返回true

  • Object.keys()可返回自身[[Enumerable]]的属性组成的数组,不包括原型链上继承的属性
    Object.keys({a:1})返回["a"],不包含原型链上的toString等内容

  • Object.getOwnPropertyNames()可以返回自身任何属性组成的数组,不包括原型链上继承的属性

类目语句自身属性原型链上继承的属性
可枚举属性不可枚举属性可枚举属性不可枚举属性
访问obj.prop
obj[“prop”]
循环for key in obj
判断key in objTRUETRUETRUETRUE
obj.hasOwnProperty(key)TRUETRUEFALSEFALSE
列举Object.keys(obj)
Object.getOwnPropertyNames(obj)

可以通过以下方式避免遍历过程中的原型链干扰:

  • 在get/set方法中为每一个键加上前缀

  • Object.create(null)来创建一个没有原型的对象

这些都可以在StringMap的解决方案里找到:
(虽然很不喜欢粘代码,但是google code都快关了)

// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Implements StringMap - a map api for strings.
 *
 * @author Mark S. Miller
 * @author Jasvir Nagra
 * @requires ses
 * @overrides StringMap
 */

var StringMap;

(function() {
   'use strict';

   var create = Object.create;
   var freeze = Object.freeze;
   function constFunc(func) {
     func.prototype = null;
     return freeze(func);
   }

   function assertString(x) {
     if ('string' !== typeof(x)) {
       throw new TypeError('Not a string: ' + x);
     }
     return x;
   }

   var createNull;

   if (typeof ses === 'undefined' ||
       !ses.ok() ||
       ses.es5ProblemReports.FREEZING_BREAKS_PROTOTYPES.beforeFailure) {

     // Object.create(null) may be broken; fall back to ES3-style implementation
     // (safe because we suffix keys anyway).
     createNull = function() { return {}; };
   } else {
     createNull = function() { return Object.create(null); };
   }

   StringMap = function StringMap() {

     var objAsMap = createNull();

     return freeze({
       get: constFunc(function(key) {
         return objAsMap[assertString(key) + '$'];
       }),
       set: constFunc(function(key, value) {
         objAsMap[assertString(key) + '$'] = value;
       }),
       has: constFunc(function(key) {
         return (assertString(key) + '$') in objAsMap;
       }),
       'delete': constFunc(function(key) {
         return delete objAsMap[assertString(key) + '$'];
       })
     });
   };

 })();
    原文作者:Humphry
    原文地址: https://segmentfault.com/a/1190000002425003
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞