Java Reference
In-Depth Information
Nashorn contains few array-like objects such as the String and arguments objects.
Most of the methods in the Array.prototype object are generic, meaning that they can
be invoked on any array-like objects, not necessarily only on arrays. The following code
shows how to call the join() method of the Array.prototype object on an array-like
object:
// An array-like object
var list = {"0":"Fu", "1":"Su", "2":"Li", length:3};
var joinedList = Array.prototype.join.call(list, "-");
print(joinedList);
Fu-Su-Li
The String object is also an array-like object. It maintains a read-only length
property and each character has an index as its property name. You can perform the
following array-like operations on strings:
// A String obejct
var str = new String("ZIP");
print("str[0] = " + str[0]);
print("str[1] = " + str[1]);
print("str[2] = " + str[2]);
print('str["length"] = ' + str["length"]);
You could have achieved the same results using the charAt() and length() methods
of the String object. The following code converts a string to uppercase, removes vowels of
English alphabets, and joins all characters using a hyphen as the separator. All are done
using the methods on the Array.prototype object as if the string is an array of characters:
// A String object
var str = new String("Nashorn");
// Use the map-filter-reduce patern on the string
var newStr = Array.prototype.map.call(str, (function (v, i, d)
v.toUpperCase()))
.filter(function (v, i, d) (v !== "A" && v !== 'E' && v !== 'I' && v !==
'O' && v !== 'U'))
.reduce(function(prev, cur, i, data) prev + "-" + cur);
print("Original string: " + str);
print("New string: " + newStr);
Original string: Nashorn
New string: N-S-H-R-N
Search WWH ::




Custom Search