JavaScript 逻辑与赋值(&&=)运算符
这个运算符用 x &&= y表示,它被称为逻辑与赋值运算符。它只在 x 为真值时将 y 的值赋值给 x 。
我们使用这个运算符 x &&= y来进行操作。现在将这个表达式分为两部分, x && (x = y)。 如果x的值为true,那么 (x = y) 语句就会执行,y的值就会存储到x中;但是如果x的值为假值,那么 (x = y) 语句就不会执行。
语法:
x &&= y
是等同于
x && (x = y)
示例: 此示例演示了JavaScript的逻辑与赋值(&&=)运算符的基本用法。
<script>
let name = {
firstName: "Ram",
lastName: "",
};
console.log(name.firstName);
// Changing the value using logical
// AND assignment operator
name.firstName &&= "Shyam";
// Here the value changed because
// name.firstName is truthy
console.log(name.firstName);
console.log(name.lastName);
// Changing the value using logical
// AND assignment operator
name.lastName &&= "Kumar";
// Here the value remains unchanged
// because name.lastName is falsy
console.log(name.lastName);
</script>
输出:
"Ram"
"Shyam"
""
""
示例2: 此示例演示了Javascript逻辑AND赋值(&&=)运算符的基本用法。
<h1 style="color:green">
Geeksforgeeks
</h1>
<h3>
Javascript Logical AND assignment(&&=) operator
</h3>
<p id="print_arr"></p>
<script>
let arr = [1, 2, "apple", null, undefined, []]
// Replace each truthy values with "gfg"
arr.forEach((item, index)=>{
arr[index] &&= "gfg"
})
document.getElementById("print_arr").innerText = arr.toString();
//console.log(arr)
</script>
输出:

我们有一个完整的JavaScript运算符列表,请查阅 JavaScript运算符完整参考 文章。
支持的浏览器:
- Chrome 85
- Edge 85
- Firefox 79
- Safari 14
极客教程