- MooTools 1.3 Cookbook
- Jay Larry G. Johnston
- 374字
- 2021-04-02 19:07:06
Looping over an array of names and saying "Hello" to all of them
In this recipe we will be looping over an array of names and saying "Hello" to each of them.
Getting ready
To initialize our list of names, we look to the United States' President, Barack Obama, who did an interview in 2008 with Rolling Stone magazine and mentioned the oldies musicians found on his iPod. Let's loop over that list and say, 'Hello' to each of them.
How to do it...
Use literal JavaScript array definition to put the array values in an object array, var obamas_oldies = ['Stevie Wonder', 'a lot of Bob Dylan', 'a lot of Rolling Stones', 'a lot of Miles Davis', 'John Coltrane']
;Using either of the other types of array object instantiation syntax would not affect this example.
<script type="text/javascript" src="mootools-1.3.0.js"></script> </head> <body> Hello Bulletin Board:<br/> <div id="hello_board"></div> <script type="text/javascript"> var oldies = ['Stevie Wonder', 'a lot of Bob Dylan', 'a lot of Rolling Stones', 'a lot of Miles Davis', 'John Coltrane']; var hb = $('hello_board'); // iterating an array using a bound function obamas_oldies.each( function(oldie, index){ hb.set('html',hb.get('html')+'<br/>Hello '+oldie+', you are number '+index+' on the Obama playlist!'); } ); </script>
How it works...
Once we have an array of values, it is inevitable that we will need to loop over them. Iterating through array values is made mooch more simple by our JavaScript abstraction layer's iteration methods, each()
and forEach()
, which extend when a browser does not have, built-in, a forEach()
iterator. The two methods are identical.
In the example, for effect, a line break is separating the each()
opening and the beginning of the mandatory first argument, the callback function. There does not need to be a space here; usually, programmers write the first line (including the optional secondary argument) as such:
obamas_oldies.each(function(oldie, index){
On the final line, the closing curly brace of the function and the closing parenthesis of the argument are nearly always sandwiched together:
});
The get()
and set()
method of the $-defined DOM object allow us to inject the HTML message(s).
See also
When we return to the MooTools online documentation to learn more about the get()
and set()
methods, we really prepare ourselves to become MooTool aficionados, ready at a moment's notice to help a friend or coworker with their Moo-predicaments.
- Joomla! 1.5 Site Blueprints
- MATLAB計算機視覺經典應用
- 常用工具軟件案例教程
- 中文版CorelDRAW 2022基礎教程
- 設計模式之禪(第2版)
- Joomla! 1.5 SEO
- 穿越Photoshop CC
- 斯科特·凱爾比的零基礎攝影后期課 Lightroom數碼照片調修技法
- 中文版Photoshop CS6平面設計實用教程(第2版)
- PHP應用開發與實踐
- Creo 4.0從入門到精通
- 新編AutoCAD制圖快捷命令速查一冊通
- Vue 企業開發實戰
- Maya 2015從入門到精通
- SilverStripe 2.4 Module Extension, Themes, and Widgets: Beginner's Guide