menu
首页文章相册工具关于
search
...

python 和 JavaScript 的不同

2026/08/27
eye-

借助 AI,一个需求我可以同时进行前后端的开发。我们公司使用的是后端语言是python,记录一下学习内容。

boolean 判断

python 用and, not, or

def is_dev():
    return (
        not is_prod()
        and not is_staging()
    )

javascript 用 !, &&, ||

function is_dev() {
  return !isProd() && !is_staging()
}

if 条件判断

python的if不强制括号,并且条件后面要加上冒号

def is_a_greater_than_b(a, b):
    if a > b:
        return "a is greater than b"
    return "a is not greater than b"

JavaScript 条件需要括号,并且不需要冒号

function is_a_greater_than_b(a, b) {
  if (a > b) return "a is greater than b"
  return "a is not greater than b"
}

运算符 ==

python 里面没有 ===, 只有==

def value_of_card(card):
    if card in {"J", "Q", "K"}:
        return 10
    # Python 没有 === ; == 不进行 JS 风格的类型强制转换
    if card == 'A':
        return 1
    return int(card)

javascript 有===

function value_of_card(card) {
  const faceSet = new Set(["J", "Q", "K"])
  if (faceSet.has(card)) return 10
  if (card === "A") return 1
  return parseInt(card)
}

三数比较大小

python 里面有链式比较

def can_double_down(card_one, card_two):
    values = {'J': 10, 'Q': 10, 'K': 10, 'A': 1}

    v1 = int(values.get(card_one, card_one))
    v2 = int(values.get(card_two, card_two))
    return 9 <= v1 + v2 <= 11

javascript只能分开处理

function can_double_down(card_one, card_two) {
  const values = { J: 10, Q: 10, K: 10, A: 1 }

  const v1 = parseInt(values[card_one] || card_one)
  const v2 = parseInt(values[card_two] || card_two)
  const total = v1 + v2
  return total >= 9 && total <= 11
}

python strip 和 js trim

python 字符串有个方法可以去掉首位空格

" hello world ".strip() # "hello world"

javascript 里面的trim()也可以实现

" hello world ".trim() // "hello world"

但是python这个方法支持参数,能力更强一点。str.strip(chars) 里 chars 参数的语义:它是一个"字符集合",不是一个要匹配的前缀/后缀字符串。

  • Python 会把 chars 拆成一个个的码点(字符),组成一个集合。
  • 然后从字符串的左端开始逐个字符检查:只要这个字符在集合里就删掉,继续看下一个;遇到第一个不在集合里的字符就停下。
  • 右端同理,从最后一个字符往回删。
  • 中间的部分永远不动。

这些字符出现的顺序、次数都无所谓,任意排列组合都会被剥掉。

"xxyyxhelloyxyy".strip("xy")   # "hello"
"hello world".strip("dlohe ")  # "wor"

第二个例子里,左边 h e l l o (空格) 都在集合中被删,遇到 w 停止;右边 d l 被删,遇到 r 停止。 最经典的坑就是拿它当"去掉前缀"用:

"https://example.com".strip("https://")  # 'example.com'  看起来对
"https://sample.com".strip("https://")   # 'ample.com'    开头的 s 也被吃掉了

因为 s 在集合 {h, t, p, s, :, /} 里,删完 // 之后它继续往右吃。

如果真的要去掉固定的前后缀,用 Python 3.9+ 的 removeprefix() / removesuffix()

"https://sample.com".removeprefix("https://")  # 'sample.com'

不传参数时,chars 默认是所有空白字符(空格、\t、\n、\r 等),同样是任意组合都会被剥掉:" \t\n hi \n ".strip() → 'hi'。另外还有只处理一端的 lstrip() 和 rstrip()。

python join and js join

python里面的join功能和js的差不多,但是语法不一样。连接词写在前面

def make_word_groups(vocab_words):
    prefix = vocab_words[0]
    # 分隔符里嵌入前缀:join 只在元素间插入,首个元素自然保持裸前缀
    return (" :: " + prefix).join(vocab_words)

make_word_groups(['en', 'close', 'joy', 'lighten']) # en :: enclose :: enjoy :: enlighten

JavaScript的join写在后面:

function make_word_groups(vocab_words) {
  const prefix = vocab_words[0]
  return vocab_words.join(` :: ${prefix}`) // 'en :: enclose :: enjoy :: enlighten'
}

Python 的 str.join() 要求所有元素都是字符串,遇到数字会抛 TypeError,得先 map(str, ...)。JS 的 Array.prototype.join() 会自动转换,null 和 undefined 还会变成空字符串。

计算数组的和

python 里面有一个sum(list) 函数,可以直接获取list的总和。

def card_average(hand):
    """Calculate and returns the average card value from the list.

    Parameters:
        hand (list): The cards in the hand.

    Returns:
        float: The average value of the cards in the hand.
    """

    return sum(hand) / len(hand)

JavaScript 里面没有现成的对数组求和的方法,需要手动处理:

function card_average(hand) {
  const sum = hand.reduce((sum, item) => sum + item, 0)
  return sum / hand.length
}

向下取整

python里面的 //和js的Math.floor 类似。 python

`mid = (low + high) // 2`

js

mid = Math.floor((low + high) / 2)

满足条件的元素的数量

python可以使用列表推导式,然后用sum直接对list进行求和:

def count_failed_students(student_scores):
  return sum(1 for score in student_scores if score <= 40)

javascript需要使用filter:

function count_failed_students(student_scores) {
  return student_scores.filter((score) => score <= 40).length
}
单一数据源颜色管理实现文件上传组件
目录
  • boolean 判断
  • if 条件判断
  • 运算符 ==
  • 三数比较大小
  • python strip 和 js trim
  • python join and js join
  • 计算数组的和
  • 向下取整
  • 满足条件的元素的数量