Applying a Function Against Each Array Element
Problem
You want to use a function to check an array value, and replace it if it matches a given criterion.
Solution
Use the Array method forEach() to apply a callback function to each array element:
var charSets = ["ab","bb","cd","ab","cc","ab","dd","ab"]; function replaceElement(element,index,array) { if (element == "ab") array[index] = "**"; } // apply function to each array element charSets.forEach(replaceElement); console.log(charSets); // ["**", "bb", "cd", "**", "cc", "**", "dd", "**"]
EXPLAIN
we used a while loop to traverse an array and replace a value. Most of the tedious bits are eliminated by using the forEach() method. The forEach() method takes one argument, the callback function. The function itself has three parameters: the array element, an index of the element, and the array. All three were used in the function, replaceElement, though only the first argument is required. In the function, the value is tested to see if it matches a given string, ab. If matched, the array element’s index is used to modify the array element’s value with the replacement string, **.
About That Conditional Statement The solution used a single line for the conditional statement, sans braces:
if (element == "ab") array[index] = "**";
Using this single line syntax without braces can be frowned upon because it doesn’t account for the possibility of future additions to the conditional block:
if (element == "ab") { array[index] = "**"; //some other line of code }
However, we should be aware of what we’re doing with our code, enough so that we’ll know if there’s a strong possibility of additional code within the conditional block. I don’t see any harm in using a single line when warranted, such as when the conditional stands alone and isn’t part of an if-then-else construct. Of course, we can be even more cryptic and use the following:
(element == "ab") && (array[index] = "**");
If the element has a value of ab, the assignment in the second set of parenthesis is performed. This syntax not only works, it can be faster than the original approach. However, those not familiar with this cryptic conditional could have problems under‐ standing what’s happening, as the approach is less readable than using the traditional if statement.
No comments:
Post a Comment