Compare Python and JavaScript array loops

I mainly use Python, but when I touch JavaScript, there are various array operations and I get confused, so I organized it.

theme

This time, the theme is a program that loops an array containing strings and returns an array with __ at the end of all elements.

Python

for in In Python, there is only one basic for statement. You can iterate with for i in <list>.

from typing import List
array = ["hoge", "fuga", "foo", "bar"]

def add_suffix(text: str) -> str:
    return text + "__"

def for_in(array: List[str]) -> List[str]:
    ls: list = []
    for item in array:
        ls.append(add_suffix(item))
    return ls

print(for_map(array))
# ['hoge__', 'fuga__', 'foo__', 'bar__']

map
You can use map to apply a function to all arrays. However, the return value of the map method is an iterator called a map object, so it needs to be converted to a list.

def for_map(array: List[str]) -> List[str]:
    return list(map(add_suffix, array))

print(for_in(array))
# ['hoge__', 'fuga__', 'foo__', 'bar__']

enumerate
If you need an index, you can use ʻenumerate`.

def for_enum(array: List[str]) -> List[str]:
    ls: list = []
    for idx, item in enumerate(array):
        # idx = 0, 1, 2, 3
        ls.append(add_suffix(item))
    return ls

print(for_enum(array))
# ['hoge__', 'fuga__', 'foo__', 'bar__']

JavaScript

for In JavaScript, there are various description methods, but the basic one is probably the same style as C language.

var array = ["hoge", "fuga", "foo", "bar"];

function add_suffix(text) {
  return text + "__";
}

function forI(array) {
  returnArray = new Array();
  for (var i = 0; i < array.length; i++) {
    // i = 0, 1, 2, 3
    returnArray.push(add_suffix(array[i]));
  }
  return returnArray;
}

console.log(forI(array));
// ['hoge__', 'fuga__', 'foo__', 'bar__']

for in
var i in array loops the properties of the object. Since the property of the ʻArray object is an array of integer values, the above counter can be retrieved. However, note that ʻidx here is a string type.

function forIn(array) {
  returnArray = new Array();
  for (var idx in array) {
    // idx = "0", "1", "2", "3"
    returnArray.push(add_suffix(array[idx]));
  }
  return returnArray;
}

console.log(forIn(array));
// ['hoge__', 'fuga__', 'foo__', 'bar__']

However, this method is not recommended for arrays where the order is important because the iteration order is implementation dependent. for...in - JavaScript _ MDN

Note: for ... in should not be used for array iterations where index order is important.

Because the order of the iterations is implementation-dependent, array iterations do not always refer to the elements in a consistent order. For this reason, it is better to use a for loop (or Array.prototype.forEach () or for ... of loop) with a numeric index when repeating an array where the order of access is important.

for of
You can use for of from ECMAScript6. This behavior is familiar to Python users. The contents of the array itself are retrieved.

function forOf(array) {
  returnArray = new Array();
  for (var item of array) {
    returnArray.push(add_suffix(item));
  }
  return returnArray;
}

console.log(forOf(array));
// ['hoge__', 'fuga__', 'foo__', 'bar__']

forEach
You can use ʻArray.prototype.forEach ()` to execute one function for each element. Array.prototype.forEach() - JavaScript _ MDN

The forEach () method executes the given function once for each element of the array.

function forEach(array) {
  returnArray = new Array();
  array.forEach(item => {
    returnArray.push(add_suffix(item));
  });
  return returnArray;
}

console.log(forEach(array));
// ['hoge__', 'fuga__', 'foo__', 'bar__']

The difference from for of is that you cannot break in the middle except to raise an exception. Also, if the element is ʻundefined`, the function will not be called. However, it can be used with IE9 or above.

map
The last is map, which applies the function to all the elements of the array. Unlike Python, the return value is ʻArray`.

function forMap(array) {
  return array.map(add_suffix);
}

console.log(forMap(array));
// ['hoge__', 'fuga__', 'foo__', 'bar__']

Recommended Posts

Compare Python and JavaScript array loops
Differences in authenticity between Python and JavaScript
Avoid nested loops in PHP and Python
Python> link> 2D array initialization and assignment
Python multidimensional array
[Beginner] Python array
[Super basic] Compare Python, Java and JavaScript (variable, if statement, while statement, for statement)
Python array basics
Correspondence summary of array operation of ruby and python
Compare the speed of Python append and map
Compare xml parsing speeds with Python and Go
[Python] Learn about asynchronous programming and event loops
[python] Compress and decompress
About Python for loops
Python and numpy tips
[Python] pip and wheel
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
Ruby, Python and map
python numpy array calculation
python input and output
Python and Ruby split
Compare strings in Python
Python3, venv and Ansible
Compare "relationship between log and infinity" in Gauche (0.9.4) and Python (3.5.1)
Python asyncio and ContextVar
Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
[python] Array slice operation
Compare HTTP GET / POST with cURL (command) and Python (programming)
How to swap elements in an array in Python, and how to reverse an array.
Python> Difference between inpbt and print (inpbt) output> [1. 2. 3.] / array ([1., 2., 3.], dtype = float32)
Remove leading and trailing whitespace in Python, JavaScript, or Java
Programming with Python and Tkinter
Encryption and decryption with Python
Python memo (for myself): Array
Python: Class and instance variables
Quicksort an array in Python 3
3-3, Python strings and character codes
Python 2 series and 3 series (Anaconda edition)
Python and hardware-Using RS232C with Python-
Python on Ruby and angry Ruby on Python
Python indentation and string format
Install Python and Flask (Windows 10)
About python objects and classes
About Python variables and objects
Apache mod_auth_tkt and Python AuthTkt
Compare the Python array-like guys
Å (Ongustromu) and NFC @ Python
Python: 3D array image (numpy.array)
Understand Python packages and modules
# 2 [python3] Separation and comment out
Python shallow copy and deep copy
Python and ruby slice memo
Python installation and basic grammar
I compared Java and Python!
Python shallow and deep copy
Stumble story with Python array
About Python, len () and randint ()
About Python datetime and timezone
Install Python 3.7 and Django 3.0 (CentOS)