Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array is converted to string while adding elements to it from other array

I'm at the start of the road so bear with me. The issue is presented in the title.The code i'm using is as followed:

var arr = [7, 29, 8, 33, 37, 4, -31, 39, 32, -12, 9];
var even = [];
for (var i = 0; i < arr.length; i++){
        if(arr[i]%2 == 0){
            even += arr[i];
        }
    }
console.log(even.length);

The code should just get the even elements from an array and move it to another. When the code is ran, the variable "even" will hold the elements as "8432" instead of [8, 4, 32], which will give me a wrong result in console at the end: "4" instead of "3". I can't figure it out why would behave like this.

like image 800
user3477993 Avatar asked Apr 20 '16 19:04

user3477993


People also ask

How do I convert an array to a string?

1 In the above code, we first declared an array with the name $arra and assigned some values. ... 2 To show the original, we have used the Print_r function, which displays each element of the array separately. 3 And then, we have used the implode () function that will convert all the array elements into a string. ... More items...

How to convert array elements into strings in PHP?

We will be working on three ways to convert array elements into strings in PHP. The IMPLODE () function is a built-in PHP function that is mainly used to join all the elements of a declared array.

What happens when array elements are joined together?

When all the array elements are joined together, they form a string, implode () works similarly to the joint () function in PHP, and return the value as a string. NOTE: - The array is represented in the form of a string, but the base data type remains array. If we use the gettype () function on the converted string, it will still show an array.

Is it possible to assign a string to an object[] array?

1 - In Java, an Object [] is not assignment compatible with a String []. If it was, then you could do this: Object [] objects = new Object [] {new Cat ("fluffy")}; Dog [] dogs = (Dog []) objects; Dog d = dogs [0]; // Huh??? This is clearly nonsense, and that is why array types are not generally assignment compatible.


1 Answers

Try

even.push(arr[i])

instead of

even += arr[i];

See http://www.w3schools.com/jsref/jsref_push.asp for more example

like image 192
Tim B Avatar answered Sep 28 '22 03:09

Tim B