编程小贴士

给你的编程提供小点子


Javascript数组方法探究一二

1. Array.prototype.slice方法
数组的 slice 方法通常用来从一个数组中抽取片断。不过,它还有将“类数组”(比如arguments和?HTMLCollection?)转换为真正数组的本领。

var nodesArr = Array.prototype.slice.call(document.forms);
var argsArr = Array.prototype.slice.call(arguments);

我就好奇了为什么数组的slice方法有这样的本领,它在javascript引擎中是如何实现的?slice的兄弟方法有没有这样的本领?

带着好奇心,下载Google的V8 javascript引擎源码到本地,V8源码的下载地址:https://github.com/v8/v8。

在v8-master/src/array.js中查找“Array.prototype.slice”:

function ArraySlice(start, end) {
CHECK_OBJECT_COERCIBLE(this, “Array.prototype.slice”);

var result = []; // 这句是关键

if (end_i < start_i) return result;

if (UseSparseVariant(array, len, IS_ARRAY(array), end_i – start_i)) {

SparseSlice(array, start_i, end_i – start_i, len, result);
} else {
SimpleSlice(array, start_i, end_i – start_i, len, result);
}

return result;

接着猜想调用“类数组”走的应该是SimpleSlice方法,然后在源码查找“SimpleSlice“,发现Array.prototype.splice源码中也调用了SimpleSlice方法,且结果变量也初始化为空数组。不过,想用splice方法把“类数组”转化为真正数组,必须要传入起始位置参数为0,即:

var nodesArr = Array.prototype.splice.call(document.forms, 0);

因为它的实现原理就是将被删除的数组项组成新数组。感兴趣的童鞋可以看下Array.prototype.splice的源码实现。
此外,slice还可以克隆一个数组:

1 var arr = [1, 2, 3];
2 var cloneArr = arr.slice(); // cloneArr:  [1, 2, 3]

2. Array.prototype.push 方法
使用 push方法可以合并数组:

1 var arr1 = [1, ‘str’, {name: ‘lang’}];
2 var arr2 = [2, ‘ing’];
3 Array.prototype.push.apply(arr1, arr2);
4 // 返回结果:[1, “str”, {name: ‘lang’}, 2, “ing”]

3. Array.prototype.sort 方法
先上代码:

var arr = [‘1′, ‘2’, ’10’, ’12’];
arr.sort();
// 返回结果:[“1″, “10”, “12”, “2”]

上面的结果通常不是我们想要的,那么如何按数值大小排序:

arr.sort(function(a, b) {
return a – b;
})
// 返回结果:[“1″, “2”, “10”, “12”]

有了排序比较器函数之后,就可以自定义很多比较器,从而实现个性化的排序。

4. length 属性
数组的length属性,不是只读的,也就说还可写哦,比如使用length属性去截断数组:

1 var arr = [1, 2, 3, 4];
2 arr.length = 2;
3 // arr: [1, 2]
4 arr.length = 0;
5 // arr: []

与此同时,如果把length属性变大,数组的长度值变会增加,且使用undefined来作为新的元素填充。

1 var arr = [];
2 arr.length = 3;
3 // arr: [undefined, undefined, undefined]

87 Responses to “ Javascript数组方法探究一二 ”

  1. see pron说道:

    e6W9tE standards. Search for to strive this inside just a bar or membership.

  2. It as difficult to find well-informed people in this particular subject, however, you seem like you know what you are talking about! Thanks

  3. colors for kids说道:

    Very nice post i must say wedkarstwo.Very nice post i must say wedkarstwo.Very nice post i must say wedkarstwo.Very nice post i must say wedkarstwo.Very nice post i must say wedkarstwo.

  4. Lung Health说道:

    Thanks so much for the blog.Thanks Again. Will read on

  5. You have remarked very interesting points ! ps nice website.

  6. to learn more说道:

    It as fantastic that you are getting thoughts from

  7. Wow! Thank you! I permanently needed to write on my blog something like that. Can I implement a fragment of your post to my site?

  8. Oluwadamilare说道:

    Very nice post and right to the point. I am not sure if this is actually the best place to ask but do you folks have any thoughts on where to get some professional writers? Thx

  9. buy lol smurfs说道:

    This blog is no doubt awesome as well as informative. I have chosen many helpful tips out of it. I ad love to visit it again soon. Thanks a bunch!

  10. our website说道:

    My brother suggested I might like this websiteHe was once totally rightThis post truly made my dayYou can not imagine simply how a lot time I had spent for this information! Thanks!

  11. home说道:

    You completed various fine points there. I did a search on the topic and found most folks will have the same opinion with your blog.

  12. w88world说道:

    Utilisation sex toys masturbation lesson

  13. This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your fantastic post. Also, I ave shared your website in my social networks!

  14. Thank you for your article post.Much thanks again. Awesome.

  15. Thanks for sharing, this is a fantastic blog post.Really thank you! Keep writing.

  16. Wholesale Cheap Handbags Will you be ok merely repost this on my site? I ave to allow credit where it can be due. Have got a great day!

  17. Airport taxi说道:

    There is perceptibly a bunch to identify about this. I suppose you made some good points in features also.

  18. Woah this is just an insane amount of information, must of taken ages to compile so cheers so much for just sharing it with all of us.

  19. click here说道:

    Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is great, as well as the content!

  20. It as hard to find well-informed people in this particular subject, but you seem like you know what you are talking about! Thanks

  21. Green Card说道:

    Just a smiling visitor here to share the love (:, btw great pattern.

  22. our website说道:

    Muchos Gracias for your article.Really thank you!

  23. Nwokolo说道:

    Many thanks for sharing this great article. Very inspiring! (as always, btw)

  24. klm voucher说道:

    It as really a cool and helpful piece of info. I am glad that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.

  25. Many thanks for sharing this first-class article. Very interesting ideas! (as always, btw)

  26. Terrific Post.thanks for share..much more wait..

  27. you got a very excellent website, Glad I observed it through yahoo.

  28. to read more说道:

    Thanks for the article.Much thanks again. Keep writing.

  29. This is one awesome post.Much thanks again.

  30. Very fine agree to, i beyond doubt care for this website, clutch resting on it.

  31. phu kien mac说道:

    It as in fact very complicated in this active life to listen news on Television, therefore I simply use world wide web for that purpose, and take the hottest information.

  32. pay day loans说道:

    Remarkable issues here. I am very happy to

  33. giay nam cong so说道:

    Say, you got a nice blog.Really looking forward to read more. Really Cool.

  34. The time to read or go to the material or web-sites we have linked to beneath.

  35. Thank you for another wonderful article. Where else could anybody get that kind of info in such a perfect way of writing? I have a presentation next week, and I am on the look for such information.

  36. Wow! This could be one particular of the most helpful blogs We have ever arrive across on this subject. Actually Fantastic. I am also an expert in this topic therefore I can understand your effort.

  37. fashion说道:

    You made some decent points there. I did a search on the topic and found most persons will approve with your site.

  38. News说道:

    You made several fine points there. I did a search on the topic and found a good number of people will have the same opinion with your blog.

  39. belly fat drink说道:

    Im thankful for the article post.Much thanks again. Cool.

  40. reading science fiction books is the stuff that i am always into. science fiction really widens my imagination*

  41. Tejido de punto说道:

    Some really excellent information, Gladiola I observed this.

  42. Really enjoyed this article. Really Great.

  43. local说道:

    Thanks pertaining to discussing the following superb written content on your site. I ran into it on the search engines. I will check back again if you publish extra aricles.

  44. Ipad keyboard case view of Three Gorges | Wonder Travel Blog

  45. School news说道:

    You made some good points there. I checked on the internet to learn more about the issue and found most people will go along with your views on this website.

  46. ps4 ark servers说道:

    Wow, fantastic blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is wonderful, as well as the content!

  47. Wow! I cant think I have found your weblog. Very useful information.

  48. Thanks-a-mundo for the article post. Really Cool.

  49. Shira说道:

    I truly appreciate this blog.Much thanks again. Will read on

  50. This is a really great examine for me, Must admit that you are a single of the best bloggers I ever saw.Thanks for posting this informative article.

  51. There as noticeably a bundle to find out about this. I assume you made certain nice points in features also.

  52. ventas说道:

    Wow, great blog article.Thanks Again. Fantastic.

  53. You made some clear points there. I did a search on the topic and found most guys will approve with your site.

  54. free browsing说道:

    This excellent website really has all of the information I wanted concerning this subject and didn at know who to ask.

  55. traveler说道:

    Website We Recommend You made some fine points there. I did a search on the matter and found most people will consent with your blog.

  56. Thanks a lot for the blog article.Much thanks again. Awesome.

  57. girl games 3说道:

    Wow, great post.Really thank you! Much obliged.

  58. Im obliged for the article.Much thanks again.

  59. wholesale说道:

    The web is really useful for me and all people studying English. The quality of podcast is good and I hope there will be more useful and interesting lessons. Thanks!

  60. Wow, what a video it is! Actually fastidious feature video, the lesson given in this video is actually informative.

  61. IaаАа’б‚Т€ТšаЂаŒаАа’б‚Т€ТžаБТžve been absent for some time, but now I remember why I used to love this weblog. Thank you, I will try and check back much more often. How regularly you update your internet web site?

  62. This is really interesting, You are a very skilled blogger. I ave joined your feed and look forward to seeking more of your fantastic post. Also, I ave shared your website in my social networks!

  63. It is nearly not possible to find knowledgeable folks about this topic, but the truth is sound like do you realize what you are coping with! Thanks

  64. go to说道:

    Very informative blog.Thanks Again. Really Cool.

  65. Keep up the fantastic piece of work, I read few articles on this website and I conceive that your website is really interesting and contains sets of great information.

  66. Very nice post. I absolutely love this website. Keep it up!

  67. you can check说道:

    Wow, great blog article.Really looking forward to read more. Fantastic.

  68. Thanks for a marvelous posting! I definitely enjoyed reading it, you can be a

  69. Share说道:

    Wow, incredible blog structure! How lengthy have you been running a blog for? you made blogging glance easy. The full glance of your site is great, let alone the content!

  70. facebook说道:

    Lovely blog! I am loving it!! Will be back later to read some more. I am bookmarking your feeds also.

  71. check说道:

    Im thankful for the article.Really looking forward to read more. Fantastic.

  72. or understanding more. Thanks for wonderful information I was looking for this information for my mission.

  73. post an ad说道:

    information with us. Please keep us up to date like this.

  74. more details说道:

    Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something.

  75. Keep up the great work , I read few posts on this web site and I believe that your website is rattling interesting and has bands of good info.

  76. website说道:

    I think this is a real great article post.Really looking forward to read more. Much obliged.

  77. daftar pb garena说道:

    Major thanks for the post.Really thank you! Awesome.

  78. official site说道:

    This blog is without a doubt awesome additionally amusing. I have found a bunch of interesting tips out of this source. I ad love to return again soon. Thanks a lot!

  79. more info说道:

    This is very interesting, You are a very skilled blogger. I ave joined your feed and look forward to seeking more of your magnificent post. Also, I ave shared your site in my social networks!

  80. orlando seo说道:

    wow, awesome article post.Really looking forward to read more. Really Great.

  81. to my followers! Excellent blog and outstanding design.

  82. click here说道:

    Wow, great article.Much thanks again. Cool.

  83. good morning说道:

    I will right away grasp your rss as I can at in finding your email subscription hyperlink or newsletter service. Do you have any? Please allow me realize so that I may subscribe. Thanks.

  84. Just discovered this blog through Yahoo, what a way to brighten up my day!

  85. Just Browsing While I was browsing yesterday I noticed a great post concerning

  86. flycam说道:

    There is certainly a lot to find out about this topic. I like all the points you made.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>