Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

google closure library - Array-like object in javascript

Looking through the dom.js source from the Closure library I found this (in goog.dom.getElementsByTagNameAndClass_):

if (opt_class) {
var arrayLike = {};
var len = 0;
for (var i = 0, el; el = els[i]; i++) {
  var className = el.className;
  // Check if className has a split function since SVG className does not.
  if (typeof className.split == 'function' &&
      goog.array.contains(className.split(' '), opt_class)) {
    arrayLike[len++] = el;
  }
}
arrayLike.length = len;
return arrayLike;
}

What would be the benefit of doing this over a regular array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The author of the code used empty JavaScript object as a basis of a array like object, i.e. the one that can be accessed by index and has a length property.

There could be two reasons that I could think of:

  1. memory use - if array is backed by implementation that allocates n elements, when it reaches it's limits it grows by some factor to increase it's capacity, and thusly wastes capacity - length of memory
  2. cpu time - implementor choose insertion speed over random access speed -- a return from this method is more likely to be iterated over sequentially than random accessed, and resizing the array in insertion causes allocation-copy-deallocation which has a cpu penalty

I'm betting that similar code would be found in other JavaScript libraries, and that it's result of benchmarking and finding the best to fit solution across different browsers.

edited after comment by Justin

Upon further googling it appears that array-like objects are common among JavaScript developers: checkout JavaScript: the definitive guide by David Flanagan, it has a whole sub-chapter on Array-like objects. Also these guys mention them.

No mention of why should one prefer array-like vs array object. This could be a good SO question.

So a third option could be the key: compliance with norms of JavaScript API's.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...