JavaScript arrays

While reading a book about JavaScript, I came across an example:

var names = new Array("Paul","Catherine","Steve");
var ages = new Array(31,29,34);
var concatArray;
concatArray = names.concat(ages);

My question is why the variable concatArrayshould not be defined as new Array()to store the concatenated data for both name and age arrays , but when I try to treat it concatArrayas an array by adding another line of code " document.write(concatArray[0])", it works exactly like an array, and shows me the data stored in the first element. I'm just wondering why I am not declaring it concatArrayas a new array, but it still works as one.

+3
source share
6 answers

Javascript . , - , .

, undefined:

var answer;
// now the variable exists, but it doesn't have a value
answer = 42;
// now the variable has the numerical value 42
answer = "hello";
// now the numerical value has been replaced with the string value "hello"
answer = [];
// now the variable contains an empty array
answer[0] = 1337;
// now the variable contains an array that contains an item with the value 1337
answer = -1
// now the array is gone and the variable contains the value -1
0

concatArray , . concat , . concatArray concat.

+6

Javascript, . , .

, var concatArray; , undefined:

var concatArray;
alert(typeof concatArray === "undefined");

names.concat(ages) () concatArray :

var names = new Array("Paul","Catherine","Steve");
var ages = new Array(31,29,34);
var concatArray;
alert(typeof concatArray === "undefined");
concatArray = names.concat(ages);
alert(concatArray.constructor === Array);
+3

Javascript , var, ; var concatArray, . ( concat()) javascript var .

+1

, w3schools :

concat() .

, .

w3schools

, .

+1

I would answer Andrew a little question. JavaScript variables are not strongly typed. You can put a string, then a number, and then an object in the same variable. When you use a variable, the interpreter checks that its current type is suitable for the use you are trying to make. If you write:

var a = 45;
alert(a[0]);
a = [ 5 ];
alert(a[0]);

you will get sequentially undefined, then 5.

0
source

Source: https://habr.com/ru/post/1737190/


All Articles