I was testing my code in goolge console and I found that concat() is not working as I have illustrated below:
var a = ["a"]; //undefined
a.concat("b","c"); // ["a","b","c"]
Now when I push some other string then that string replaces the indexes of "b" and "c"
that is[continued]
a.push("e","f"); // 3
a // ["a", "e","f"]
Did you notice 3 in the line where the string is pushed. It is interesting to me that at first we contact "b" and "c" and then, when I try to get value of say 1 index then it return undefined! and then, when we push "e" and "f" in the same array then these string replaces the indexes of concated string. Now the question is:
1) Why do these concat and push function show strange behavior?
2) Do this mean the failure of cancat function?
3) Is thiscontact function is just for nominal?
This is correct. Concat isn't modifying the array like you expect it to.
When you:
a.concat("b","c");
It returns an array of ["a","b","c"], but you aren't saving the reference (which you would do like this)
a = a.concat("b","c");
Some info from the MDN:
concat does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains copies of the same elements combined from the original arrays.
Related
I want to be able to create an array with only one value inside of it on the fly without using a variable. This works with a variable:
var arr = [];
arr.push('test');
console.log(arr); // correctly logs ["test"]
But this does not:
console.log([].push('test')); // logs 1
Why does this log 1 instead of ["test"]? Is this coerced into a boolean?
Array.prototype.push returns the new length of the array, not the pushed item nor the array it-self.
"I want to be able to create an array with only one value inside of it
on the fly without using a variable"
const arr = ['test'];
console.log(['test']);
Array.prototype.push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
In the first example you are first pushing the element in the array then log the array. But in the second example you are logging the returned result of push().
consider this code
example 1:
function plus(a) {return a+10}
([1]) // "110"
example 2:
var arr = [1,2,3,4,5,6,7]
arr[[1]] // 2
arr.splice([1],1);
arr // (6) [1, 3, 4, 5, 6, 7]
can someone explain why passing in an array as an argument, gets converted to a string? (that's what it looks like happened here)
can someone explain why passing in an array as an argument
It doesn't.
It gets treated as an array right up until the point where you try to use the addition operator on it.
It hits the step Let rprim be ? ToPrimitive(rval) and converts it according to those rules.
And so on until it calls the array's toString method.
Similar rules apply in the other examples.
In short: When it makes no sense at all to use an array in a given context, type conversion is applied to turn it into a data type that is apropriate.
Javascript automatically outputs a certain data type when two different data types are added.
Here are two examples:
2 + 3 // 5
2 + "hello" // "2hello"
When two numbers are added, an integer is output. However, 2 and hello can't be added numerically, so everything is first automatically converted to a string, and then appended.
The same thing happens in your case – a remains an array, but an array can't be added to a number. So both are converted to strings and then appended, and the end result is a string.
You were probablly thinking of adding a value to the end of an array. This is done using:
a.push(10);
Or, if you wanted to add the first item in the array and 10 to get the result 11, use:
return a[0] + 10
But you can't add a single number to a whole array, only to one of the items or at the end of the array.
Answer #1 - you get a string from the array.toString so you need to cast back to number - here I use +
function plus(a) {return +a+10}
console.log(plus([1]))
Second
var arr = [1,2,3,4,5,6,7]
console.log(arr[1]) // 2
console.log(arr[[1]]) // 2
arr.splice([1],1); // removes the second item
console.log(arr)
var arr = [1,2,3,4,5,6,7]
arr.splice(1,1); // just as if you had done this
console.log(arr) // [1, 3, 4, 5, 6, 7]
The + operator doesn't work for arrays. It only works for numbers or strings.
Since javascript can't use your array with the + operator, it converts it to string before. That's why plus([1]) is "110"
You can use the push method if you want to add to an array:
array.push(newElement);
In the second example, inside splice, your array is used with an operator that doesn't support it so it is converted to a number. If you look at the MDN definition of splice, you see it expects a number, not an array.
When you want to use splice, you don't pass an array as the first argument, you pass the index of the first element to remove. If you want to remove 2 from your array, you do arr.splice(1,1);
I'm trying to push an array (multiple times) into another array. Instead of an array of arrays, I'm getting all the values from the multiple push attempts as a single array. I've tried pushing an array implicitly (i.e. push([val1,val2]), explicitly creating a new Array, then pushing the new Array. Here's the key part of the code:
var coordinates=[];
...
for(i=0;i<6;i++)
{
...
for(var j=start;j<circum[i].length;j++)
{
var segmentCoords=[];
...
if(segmentFlag===false)
{
segmentCoords.push([i+1,segmentLength]);
segmentFlag=true;
}
...
if(segmentFlag===true)
{
var tempArray=new Array(i+1,segmentLength);
segmentCoords.push(tempArray);
segmentLength+=sectorLength;
coordinates.push(segmentCoords);
segmentFlag===false;
}
...
}
From the many stackoverflow questions/answers I've looked at, I expect my coordinates array to look something like this: [[val1, val2],[val3,val4],[val5,val6]]. Instead it's [val1,val2,val3,val4,val5,val6]. That is what I would expect if I were using .concat() or .apply().
Can anyone explain why my code isn't generating an array of arrays?
I've got the full code here https://jsfiddle.net/Seytom/7xm9s4qr/ in case you want to see more of it.
You seem to be fooled by your console.log. Notice the difference between these two statements:
console.log( 'string ' + [[1,2],[3,4]] ); // string, '1,2,3,4'
console.log( 'string ', [[1,2],[3,4]] ); // string, [[1,2],[3,4]]
Because you are coercing the array into a string, this is the result. Its the same as:
console.log( new Array([1,2],[3,4]).join(',') ); // 1,2,3,4
It's simply what arrays do when you join them, regardless of whether they are nested. It is better to log the array separately so you can explore it in your console, so simple print your string and then add the array as the second argument. (The console takes an infinite amount of arguments and will print them all as one statement - safari even prints the first as a special type if its a string so its clearer to read).
In short: push behaves exactly as expected, and your code should simply work as intended, but the printing to the console seems to leave a bit to be desired :).
Use Array.concat:
var arrA = [0];
var arrB = [1, 2];
while (arrA.length < 10) {
arrA = arrA.concat(arrB)
}
console.log(arrA)
The result for .join is different from .push or .pop.
var mack=[];
mack.push("dog", "cat");
mack.join(" ");
alert(mack);
Console.log: ["dog", "cat"]
var mack=[];
mack.push("dog", "cat");
alert(mack.join(" "));
Console.log: "dog cat"
In the first one, mack.join(" "); does not change the original mack array, unlike mack.push("dog", "cat"); or mack.pop();.
I'm curious that why this happened. And is there any other method like this?
The join() function doesn't change the element of array that's only represent the array elements as string with the separator what we give as argument.
here is the reference of join function
Array.prototype.join()
Array push and pop is use to add or remove element from a array that return array new size for push and element for POP.
Array.prototype.push()
Array.prototype.pop()
Here the array elements are ok as you pushed on it.
var mack=[];
mack.push("dog", "cat");
var mack_string = mack.join(" ");
console.log(mack); // Array [ "dog", "cat" ]
console.log(mack_string); // "dog cat"
Push and pop methods are used on Array object to add or remove data to/from Array and therefore change Array itself.
Join method doesn't change Array, it returns String - new object, Array remains unchanged as it is. It could be used e.g. for concatenating Strings which are put in array with particular character.
More about arrays could be found here: http://www.w3schools.com/js/js_array_methods.asp
The join() method joins all elements of an array into a string, detail
It returns a string and does not modify the original array.
Also it does not make sense to assign String for Array object, if that was your expectation.
var test = [[
[1,2],[2,3],[3,4]
]];
alert(test[[0]].length);
This returns me 3, but I cannot understand what this actually mean. How come this result?
There are no multi-dimensional arrays in JavaScript. There are only nested arrays.
[ // test
[ // test[0]
[1,2], // test[0][0]
[2,3], // test[0][1]
[3,4] // test[0][2]
] //
] //
As you can see, test[0] has a length of three.
And test[[0]] is semantically incorrect(*) and collapses into test[0].
(*) The index operator ([]) expects a number, like in test[0]. If you don't pass a number to it (like in your test[[0]] case, where you pass the array [0]), a conversion to string will happen first. (This is because of the first note below.)
Arrays are converted to string by joining their members with a comma. [0].toString() is "0", and therefore test[[0]] is equivalent to test["0"], which is equivalent to test[0].
Notes:
The square brackets are used for property access as well, so that test["length"] is the same as test.length.
Consequently, something horrible like test[[0]][["length"]]) is equivalent to test[0].length and will give you 3.
Something like test[[0,0]] would be test["0,0"] - and since there is no property named "0,0" on that array, you will get undefined.
The array test[0] contains three items:
[1,2]
[2,3]
[3,4]
Hence, the result of the length is 3.
The length of array test is just one, since test contains only one array:
[1,2],[2,3],[3,4]
In fact this is not a multi-dimensional array, it's just an array containing arrays (called a jagged array, or nested array).
test[[0]] is same thing as test[0] and test[0] is an array
[1,2],[2,3],[3,4]
consisting of these elements.
if you want to access ,for instance, [2,3] you need to use this syntax:
test[0][1]
and test[0][1].length will give you 2.
This is a nested array. An array of arrays.
It will be more clear if you expand your example:
var test = [
[
[1,2],[2,3],[3,4]
],
[
[5,6],[7,8],[9,9],[6,7]
],
];
alert(test[[1]].length);
Now, your test is an array of two arrays. The first one of which is an array of 3 arrays. The second one is an array of 4 arrays.
Now, test.length is 2. test[0].length is 3. test[1].length is 4. [[n]] just collapses.
Demo: http://jsfiddle.net/abhitalks/6H7Lj/
If you want get the length of first arrays length then write
alert(test[0][0].length);