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.
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...
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.
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.
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.
Try
even.push(arr[i])
instead of
even += arr[i];
See http://www.w3schools.com/jsref/jsref_push.asp for more example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With