1 The `map()` function creates a new array from the given input array by 2 invoking the specified callback for each item of the input array and 3 putting the resulting return value into the new array. 4 5 Returns the newly created array. The input array is not modified. 6 7 Returns `null` if the first argument is not an array. 8 9 -- Testcase -- 10 {% 11 let numbers = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]; 12 13 printf("%.J\n", 14 map(numbers, function(n) { 15 return (n * n); 16 }) 17 ); 18 %} 19 -- End -- 20 21 -- Expect stdout -- 22 [ 23 0, 24 1, 25 4, 26 9, 27 16, 28 25, 29 36, 30 49, 31 64, 32 81 33 ] 34 -- End -- 35 36 37 Supplying an invalid callback will trigger an exception. 38 39 -- Testcase -- 40 {% 41 map([1, 2, 3], "not_a_function") 42 %} 43 -- End -- 44 45 -- Expect stderr -- 46 Type error: left-hand side is not a function 47 In line 2, byte 33: 48 49 ` map([1, 2, 3], "not_a_function")` 50 Near here -------------------------^ 51 52 53 -- End -- 54 55 56 Supplying an invalid array will yield `null`. 57 58 -- Testcase -- 59 {% 60 printf("%.J\n", map("not_an_array", function(i) { return i > 3 })); 61 %} 62 -- End -- 63 64 -- Expect stdout -- 65 null 66 -- End -- 67 68 69 The callback is invoked with three argument for each item, the current item 70 value, the index position of the item and the input array being mapped. 71 72 -- Testcase -- 73 {% 74 let words = [ "foo", "bar", "baz", "qrx" ]; 75 76 print(join("\n", 77 map(words, function(word, idx, src) { 78 return sprintf("word=%s, idx=%d, src=%J", word, idx, src); 79 }) 80 ), "\n"); 81 %} 82 -- End -- 83 84 -- Expect stdout -- 85 word=foo, idx=0, src=[ "foo", "bar", "baz", "qrx" ] 86 word=bar, idx=1, src=[ "foo", "bar", "baz", "qrx" ] 87 word=baz, idx=2, src=[ "foo", "bar", "baz", "qrx" ] 88 word=qrx, idx=3, src=[ "foo", "bar", "baz", "qrx" ] 89 -- End -- 90 91 92 Exceptions in the callback terminate the map process and are 93 propagated to the calling context. 94 95 -- Testcase -- 96 {% 97 map([ 1, 2, 3 ], function() { die() }); 98 %} 99 -- End -- 100 101 -- Expect stderr -- 102 Died 103 In [anonymous function](), line 2, byte 36: 104 called from function map ([C]) 105 called from anonymous function ([stdin]:2:39) 106 107 ` map([ 1, 2, 3 ], function() { die() });` 108 Near here ----------------------------^ 109 110 111 -- End --
This page was automatically generated by LXR 0.3.1. • OpenWrt