Program/ Example of Nashorn Javascript (js) Engine in Java 8 - Create array and iterate over it, find factors using underscore-min.js >
package nashornJs;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
*
* Create array and iterate over it, find factors using underscore-min.js
*
*/
public class MyNashornClass {
public static void main(String[] args) throws Exception {
System.out.println("In java - START");
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("load('E:/pocJmse/myNashornJavaScript.js')");
System.out.println("In java - FINISH");
}
}
/* OUTPUT
In java - START
In myNashornJavaScript.js
First load the underscore-min.js
factorsOfTwo = 2,4
Create array
Iterate over array using _.each
ankit
sam
Neha
End myNashornJavaScript.js
In java - FINISH
*/
|
E:/pocJmse/myNashornJavaScript.js looks like this >
print('In myNashornJavaScript.js');
// Using filter method of UNDERSCORE-MIN.JS - To filter few specific values from array (Find factors of 2 in array)
print("First load the underscore-min.js");
load('http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js');
var myIntArray = [1, 2, 3, 4];
//Return all factors of 2
var factorsOfTwo = _.filter(myIntArray, function (num) {
return num % 2 == 0; //calculate all factors of 2
});
print("\nfactorsOfTwo = "+factorsOfTwo);
//Using each method of UNDERSCORE-MIN.JS - To iterate over elements of array
print('\nCreate array');
var myStringArray = ['ankit', 'sam', 'Neha'];
print('Iterate over array using _.each ');
_.each(myStringArray, function(str, index, myStringArray) {
print(str);
});
print('\nEnd myNashornJavaScript.js');
|
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.