Difference between JavaScript and Java
- When declaring a variable, prefix the variable name with var.
- Numbers of primitive data types are floating-point.
- How to create an array
- for in statement
- JavaScript can pass a function to another function as an argument. (Since Java 8, Java can also give a lambda expression as an argument)
We have already confirmed 1 and 2.
How to create an array
[]
Arrays created using [] provide indexes.
var arr = [1, 2, 3, 4, 5]; var sum = 0; for (var i = 0; i < arr.length; i++) { sum = sum + arr[i]; } alert('SUM:' + sum);
Array object
Arrays created using Array object provide indexes.
var arr = new Array(1, 2, 3, 4, 5); var sum = 0; for (var i = 0; i < arr.length; i++) { sum = sum + arr[i]; } alert('SUM:' + sum);
Associative array
Associative arrays have the form {key:value} and do not provide indexes. Java has no Associative arrays.
var person = {"name":"El Draque", "job":"pirate"}; alert(person.name); alert(person["name"]); alert(person.job); alert(person["job"]);
for in statement
You can access all elements of associative arrays with the for-in statement.
var person = {"name":"Barbadosed", "job":"pirate"}; var result = ""; for(var property in person) { result += person[property]; } alert(result);
JavaScript can pass functions an arguments to other functions
function x(a, y) { var ret = y(a); alert(ret); } function z(a) { return a * a } x(2, z);