Why does the foreach statement not change the element value?
You're changing the iteration variable c
. That doesn't change the contents of the array. The iteration variable is just a copy of the array element. If you want to modify the array, you need to do so explicitly:
for (int i = 0; i < array.length; i++) {
if (array[i] == 'o') {
array[i] = 'a';
}
}
Your original code is equivalent (as per section 14.14.2 of the JLS) to:
for (int i = 0; i < array.length; i++) {
char c = array[i];
if (c == 'o') {
c = 'a';
}
}
Changing the value of a local variable will never change anything else - it just changes the local variable. The assignment:
char c = array[i];
copies the value in the array into a local variable. It doesn't associate the local variable with the array element perpetually.
Why does the value in an array not change when updated in foreach?
Try replacing MYSQLI_NUM with MYSQLI_ASSOC
$wholeCountryArray = $localResult->fetch_array(MYSQLI_ASSOC);
Your loop is probably running, but rather than having the string indices that you're expecting it's just using numbers, and so it's doing
$countryCountList[0]=$countryCountList[0]+1;
rather than
$countryCountList["Italy"]=$countryCountList["Italy"]+1;
like you're thinking it is.
Why is my forEach loop not editing my array?
The forEach
method of an array does not modify the array, it just iterates over it. When you change the argument in the callback function, that doesn't affect the array either. Also, forEach
doesn't do anything with the return values from the callback. Once you calculate the value you want to use to replace, you can set it using the index and array arguments, like so.
var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4, 19, 300, 3775, 299, 36, 209, 148, 169, 299, 6, 109, 20, 58, 139, 59, 3, 1, 139];
test.forEach(function(element, index, array){ if (element % 3 === 0){ element += 100; array[index] = element; }});
console.log(test);
PowerShell - foreach() doesn't change element value
What you think you're doing is equivalent to this:
for ($i = 0; $i -lt $arr.Count; $i++) {
$arr[$i]++;
}
What you're actually doing is equivalent to this:
for ($i = 0; $i -lt $arr.Count; $i++) {
$number = $arr[$i];
$number++;
}
What you really want to do is this:
$arr = $arr | ForEach-Object { $_ + 1; }
Enhanced For Loop not changing all elements of my array
This form of the Java for
loop loops over the values, not the indexes, of the array. All of the values are 0
and you're using them as the index. You are setting the first element 5 times because of this.
Use a traditional for
loop.
for (int index = 0; index < dice.length; index++) {
// Your roll here
dice[index] = roll;
}
change values in array when doing foreach
The callback is passed the element, the index, and the array itself.
arr.forEach(function(part, index, theArray) {
theArray[index] = "hello world";
});
edit — as noted in a comment, the .forEach()
function can take a second argument, which will be used as the value of this
in each call to the callback:
arr.forEach(function(part, index) {
this[index] = "hello world";
}, arr); // use arr as this
That second example shows arr
itself being set up as this
in the callback.One might think that the array involved in the .forEach()
call might be the default value of this
, but for whatever reason it's not; this
will be undefined
if that second argument is not provided.
(Note: the above stuff about this
does not apply if the callback is a =>
function, because this
is never bound to anything when such functions are invoked.)
Also it's important to remember that there is a whole family of similar utilities provided on the Array prototype, and many questions pop up on Stackoverflow about one function or another such that the best solution is to simply pick a different tool. You've got:
forEach
for doing a thing with or to every entry in an array;filter
for producing a new array containing only qualifying entries;map
for making a one-to-one new array by transforming an existing array;some
to check whether at least one element in an array fits some description;every
to check whether all entries in an array match a description;find
to look for a value in an array
and so on. MDN link
Changing objects value in foreach loop?
You cannot change the iteration variable of a foreach-loop, but you can change members of the iteration variable. Therefore change the ChangeName
method to
private void ChangeName(StudentDTO studentDTO)
{
studentDTO.name = SomeName;
}
Note that studentDTO
is a reference type. Therefore there is no need to return the changed student. What the ChangeName
method gets, is not a copy of the student but a reference to the unique student object. The iteration variable and the studentDTOList
both reference the same student object as does the studentDTO
parameter of the method.
And change the loop to
foreach(StudentDTO student in studentDTOList)
{
ChangeName(student);
}
However, methods like ChangeName
are unusual. The way to go is to encapsulate the field in a property
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
You can then change the loop to
foreach(StudentDTO student in studentDTOList)
{
student.Name = SomeName;
}
EDIT
In a comment you say that you have to change many fields. In that case it would be okay to have a method UpdateStudent
that would do all the changes; however I still would keep the properties.
If there is no additional logic in the properties besides passing through a value, you can replace them by the handy auto-implemented properties.
public string Name { get; set; }
In that case you would have to drop the field name
.
Related Topics
How to Parse/Format Dates With Localdatetime - Java 8
Access Restriction on Class Due to Restriction on Required Library Rt.Jar
Regex For Splitting a String Using Space When Not Surrounded by Single or Double Quotes
Jcomponents Not Showing Up With Picture Background
How to Run a Java Program from the Command Line on Windows
Best Way to Format a Double Value to 2 Decimal Places
Convert String to Double in Java
How to Handle Events from Keyboard and Mouse in Full Screen Exclusive Mode in Java
Including Jars in Classpath on Commandline (Javac or Apt)
How to Prevent Java.Lang.Numberformatexception: For Input String: "N/A"
How to Compare Objects by Multiple Fields
Java 8 Lambda Function That Throws Exception
Getresourceasstream Returns Null
Which @Notnull Java Annotation Should I Use
When Does Static Class Initialization Happen
How to Open a New Tab Using Selenium Webdriver in Java
Finding the Max/Min Value in an Array of Primitives Using Java
Difference Between ≪Context:Annotation-Config≫ and ≪Context:Component-Scan≫