Huauauaa / cheat-sheet

https://huauauaa.github.io/cheat-sheet/
0 stars 0 forks source link

python & js #82

Open Huauauaa opened 4 months ago

Huauauaa commented 4 months ago

python - javascript - java

init

const books = [
  { id: 1, name: 'book1' },
  { id: 2, name: 'book2' },
];
books = [{"id": 1, "name": "book1"}, {"id": 2, "name": "book2"}]
Huauauaa commented 4 months ago

初始化二维数组

const res = Array.from({ length: 10 }, () => Array.from({ length: 10 }).fill(0));
res = [[0]*10 for i in range(10)]
Huauauaa commented 4 months ago

map

book_names = books.map((item) => item.name);
book_names = [item["name"] for item in books]
book_names = next(map(lambda item: item["name"], books))
Huauauaa commented 4 months ago

find

target = books.find((item) => item.id === 1); // {id: 1, name: 'book1'}
target = books.find((item) => item.id === 3); // undefined
target = next((item for item in books if item["id"] == 2), None)  # {'id': 2, 'name': 'book2'}
target = next((item for item in books if item["id"] == 3), None)  # None
Huauauaa commented 4 months ago

filter

res = books.filter((item) => item.id === 1);
res = books.filter((item) => item.id === 3); // []
target = list(filter(lambda item: item["id"] == 1, books))
target = list(filter(lambda item: item["id"] == 3, books))
target = next(filter(lambda item: item["id"] == 1, books), [])
target = next(filter(lambda item: item["id"] == 3, books), [])
Huauauaa commented 4 months ago

pad

const n = '10';

console.log(n.padStart(4, '*')); // **10
console.log(n.padEnd(4, '*')); // 10**
n = "10"
print(n.rjust(4, "*"))  # **10
print(n.ljust(4, "*"))  # 10**
Huauauaa commented 4 months ago

CRUD

nums = [1, 2, 3];

console.log(nums.push(5));
console.log(nums.pop());
console.log(nums.unshift(1));
console.log(nums.shift());
console.log(nums.splice(1, 0, 9));
console.log(nums);
nums = [1, 2, 3]

print(nums.append(5))
print(nums.pop())
print(nums.insert(0, 1))
print(nums.pop(0))
print(nums.insert(1, 9))
print(nums)