官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 榆社县| 青海省| 宜阳县| 延庆县| 称多县| 金堂县| 英山县| 承德市| 开远市| 苍南县| 山东| 临泉县| 十堰市| 蚌埠市| 永善县| 浙江省| 平果县| 唐山市| 新乡县| 拜城县| 宜阳县| 遂溪县| 伊宁县| 余姚市| 阳谷县| 潜江市| 土默特左旗| 沙坪坝区| 金塔县| 报价| 娄烦县| 页游| 昌黎县| 蒲江县| 深圳市| 分宜县| 杭锦后旗| 西林县| 云南省| 宜宾市| 龙海市|