1

I would like to get values from the array created inside the each loop

var arr = [];

$.each([52, 97], function(index, value) {

    var arr = [value];

});

console.log(arr);

But the logged array has no entry.

1
  • 1
    Try use .pus() method to add elemnts to your array Commented Jun 12, 2018 at 11:44

5 Answers 5

2

The error what you did is var arr = [ value]; reinitialized variable, test this:

var arr =[];
$.each([ 52, 97 ], function( index, value ) {
 arr.push(value);
});
console.log(arr);
Sign up to request clarification or add additional context in comments.

Comments

1

The error what you did is var arr = [ value]; reinitialized variable & wrong setting of array index.

var arr = [];

$.each([52, 97], function(index, value) {

  arr[index] = value;

});

console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can also do this with push() as in other answer(@Boris Bresciani).

Comments

0

You can simply use spread syntax to get the array element copied without reference. This means that you can independently change the content of any array without affecting the content of other.

var arr1 = [ 52, 97 ];
var res = [...arr1];
console.log(res);

Comments

0

Your variable arr inside the function is not the same as the outside variable arr, but local to the function. To fix that, do not create a new local variable, but let the function refer to the outside variable instead (this is called a closure). This should work:

var arr =[];
$.each([ 52, 97 ], function( index, value ) { 
  arr.push(value); 
});
console.log(arr);

Comments

0

Add value in Array using each loop in js

var ProductTypeId = [];
$("input[name=ProductTypeId]").each(function() {
    if ($(this).prop('checked') == true) {
        ProductTypeId.push($(this).val());
    }
});
alert(ProductTypeId`enter code here`);
<input type="checkbox" class="custom-control-input" name="ProductTypeId" id="<?php echo $term['productTypeId']; ?>"  value="<?php echo $term['productTypeId']; ?>">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.