开发者

Using jQuery with node.js

I have found out that you can use jQuery with node.js but all examples are for DOM and HTML manipulation.

Do you think using it for array iterations ( for each )开发者_运维技巧 etc would be ok or a bit overkill?


Most of the common jQuery utilities are already in implemented in the V8 engine, which node.js is built on.

for example, compare:

  • $.each with Array::forEach
  • $.map with Array::map
  • $.inArray with Array::indexOf
  • $.trim with String::trim

One of the best things about node.js is that most of the ES5 spec is already there.


Underscore.js is a much smaller utility library for manipulating objects.

http://documentcloud.github.com/underscore/

npm install underscore

EDIT:

However, node.js has much better support for ES5 than browsers, and it's likely that you may not even need a library for manipulating objects. See keeganwatkins' answer.


NodeJS already has all the EcmaScript 5 Array Extras builtin. For example if you want all the odd squares:

[1,2,3,4,5,6,7,8,9].map(function(n){
    return n*n;
}).filter(function(n){
    return n%2;
});
//-> [1, 9, 25, 49, 81]

If you would like to see the other methods on the arrays, you can go to my JavaScript Array Cheat Sheet.

If you want the sum of all the cubes, you can:

[1,2,3,4,5,6,7,8,9].map(function(n){
    return n * n * n;
}).reduce(function(p, n){
    return p + n;
});
//-> 2025


jQuery has some nifty non-DOM features you can borrow -

https://github.com/jquery/jquery/tree/master/src

Just strip out what you do not need (like a reference to window).


If there are just a few functions you want to add, an alternative to adding a full library is to just implement the functions you want:

Many functions that are partially supported on some browsers are documented in MDN with compatibility code that can be used to add the function: Array.forEach

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜