在 Python 中,我们使用 INLINECODE12423639 关键字来迭代元素、检查成员资格,甚至用于条件检查。JavaScript 提供了类似的功能,但在语法和行为上有所不同。这篇文章将探讨 Python 的 INLINECODE2b8ff57f 关键字在不同上下文中是如何工作的,以及我们如何在 JavaScript 中实现类似的行为。
示例:
# 用于迭代的列表
l = [1, 2, 3, 4, 5]
# 用于键检查的字典
person = {"name": "Alice", "age": 30}
# 迭代
for x in l:
print(x)
# 条件检查
if 3 in l:
print("3 is in the list")
# 字典键检查:检查键是否存在于字典中
if "age" in person:
print("Found")
输出
1
2
3
4
5
3 is in the list
Found
解释:
- INLINECODE72a41a5d 关键字在 INLINECODEea8ffb84 循环中用于遍历列表
l并打印每个元素。 - INLINECODE476c8cf8 关键字检查值 INLINECODEd844db8f 是否存在于列表
l中。 - INLINECODE432b4672 关键字检查键 INLINECODE679fd53d 是否存在于字典
person中。
让我们来探索一下 JavaScript 中的等价写法:
目录
- 迭代方面 Python 的
in在 JavaScript 中的等价写法 - 条件判断方面 Python 的
in在 JavaScript 中的等价写法 - 对象(键)方面 Python 的
in在 JavaScript 中的等价写法
迭代方面 Python 的 in 在 JavaScript 中的等价写法
在 JavaScript 中,我们可以使用 INLINECODE37e74576 来迭代数组或字符串中的元素,这类似于 Python 中用于 for 循环 的 INLINECODEd84f5840。
在 JavaScript 中迭代数组
const l = [1, 2, 3, 4, 5];
for (const x of l) {
console.log(x);
}
输出
1
2
3
4
5
解释:
- JavaScript 中的 INLINECODE34390787 循环用于遍历数组 INLINECODE4bd152e4,类似于 Python 中的
for x in l。
在 JavaScript 中迭代字符串
const s = "Hello, Shivang";
for (const char of s) {
console.log(char);
}
输出
H
e
l
l
o
,
S
h
i
v
a
n
g
解释:
- JavaScript 中的 INLINECODE1645599c 循环可用于遍历字符串中的字符,类似于 Python 中的 INLINECODEd185eb3f。
条件判断方面 Python 的 in 在 JavaScript 中的等价写法
在 JavaScript 中,我们可以使用 includes() 这样针对数组或字符串的方法来复制这种条件检查。
在 JavaScript 中的条件语句中使用 includes()
const l = [1, 2, 3, 4, 5];
const x = 3;
if (l.includes(x)) {
console.log(`${x} is in the list.`);
} else {
console.log(`${x} is not in the list.`);
}
输出
3 is in the list.
解释:
- JavaScript 中的 INLINECODE7d97a1be 方法检查 INLINECODEfc539b23 是否存在于数组 INLINECODE47ba84cb 中,类似于 Python 在 if 语句中使用的 INLINECODE95fb0b15。
在 JavaScript 中使用 includes() 检查子字符串
const s = "Hello, Shivang";
const substr = "Shivang";
if (s.includes(substr)) {
console.log(`${substr} is in the string.`);
} else {
console.log(`${substr} is not in the string.`);
}
输出
Shivang is in the string.
解释:
INLINECODE41a52082 方法检查字符串 INLINECODE6e18df2f 中是否存在子字符串 INLINECODE8576d24d,类似于 Python 与字符串一起使用时的 INLINECODEe2143cdb 关键字。
对象(键)方面 Python 的 in 在 JavaScript 中的等价写法
JavaScript 使用 INLINECODE27afdf94 操作符来检查对象中是否存在某个键。这与 Python 在字典中使用 INLINECODE4a698b5c 非常相似。
在 JavaScript 中检查对象的键
const obj = { name: ‘Shivang‘, age: 25 };
if (‘name‘ in obj) {
console.log("Key ‘name‘ is in the object.");
} else {
console.log("Key ‘name‘ is not in the object.");
}
输出
Key ‘name‘ is in the object.
解释:
- INLINECODEe7e83e59 操作符检查键 INLINECODE2b649e50 是否存在于对象 INLINECODEfe202d6f 中,类似于 Python 对字典使用 INLINECODE928b9b57 的方式。