简体   繁体   中英

Adding arrays in javascript

I have this piece of python code that I'm trying to turn into Javascript. But I'm not that familiar with Python so I'm trying to figure out what's going on here. Does anyone know what the equivalent of this is in Javascript?

res = [[0]]

for i in range(1, k):
 res = res + [subarray + [i] for subarray in res]

Since javascript behaviour for that "+ []" is different with python ( cmiiw ), you cannot do that in javascript as python could concat multi-dimensional array with "+" . So in javascript way it would be pretty similar to this. (Assume that k value is 6, as i tried your above code in python with k = 6 . The result is exactly the same).

 var res = [[0]]; var k = 6; for (i = 1; i < k; i++){ for (let subarray of res){ res = res.concat([subarray.concat([i])]) } } console.log(res);

You can translate python to javascript, you can start from trying Jiphy , RapydScript , Transcrypt

Your code seems it deals with printing all sub-arrays by accessing with the help of for loop from a multi-dimensional array.

Check List Comprehensions and Conditionals in Python. Check this link, this is similar to what you want to achieve here and also here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM