I'm adding several items to an array using concat
in an event-handler as follows:
var selectedValues = [];
$.each($('#selected-levels').data("kendoListBox").dataSource.data(), function(i, item) {
selectedValues.concat([ item.id ])
});
return {
"selected" : selectedValues
};
this always returns {level-selected: Array(0)}
even though I have checked that there are some item
s in the dataSource
(by stepping through with debugger)
why don't the items appear in the array?
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
concat() is used to merge two or more arrays. This method does not mutate the original array, but instead returns a new array populated with elements of all the arrays that were merged.
An empty array will have 0 elements inside of it.
In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.
concat
doesn't mutate the array, you need to set the value back to selectedValues
selectedValues = selectedValues.concat([ item.id ])
Or use push
selectedValues.push( item.id )
Ironically, the answer was already hidden in your question, in your question title more exactly.
Actually concat returns the correct new array you want... you just never used the return value !
You have to be aware that the array is not modified in place, but a fresh copy is returned.
So selectedValues.concat([ item.id ])
should be replaced by selectedValues = selectedValues.concat([ item.id ])
if you want to do anything.
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