ES6 判断某数组不为空时赋值给新数组的简便写法
时间: 2023-08-13 22:03:50 浏览: 59
可以使用数组的 `length` 属性和扩展运算符 `...` 来实现简便赋值:
```javascript
const oldArray = [1, 2, 3];
const newArray = oldArray.length ? [...oldArray] : [];
```
以上代码会先判断 `oldArray` 的长度是否为真(即不为 0),如果为真,则将 `oldArray` 数组的值复制到一个新的数组 `newArray` 中。如果 `oldArray` 的长度为 0,则 `newArray` 也会为空数组。
相关问题
es6 判断数组是否为空
ES6 中判断数组是否为空可以通过以下方式:
1. 使用 Array.prototype.length 属性:
```javascript
const arr = [];
if (arr.length === 0) {
console.log("数组为空");
}
```
2. 使用 Array.prototype.every() 方法:
```javascript
const arr = [];
if (arr.every((item) => !item)) {
console.log("数组为空");
}
```
在这里,我们使用 every() 方法来检查数组中的每个元素是否是 falsy 值(即 undefined、null、false、0、NaN、"")。如果数组中的所有元素都是 falsy 值,则该方法返回 true,否则返回 false。
另外,在 ES5 中,我们也可以使用 Array.prototype.length 属性或 Array.prototype.toString() 方法来判断一个数组是否为空。
es6判断数组是否包含某个对象属性
在ES6中,我们可以使用一些内置的方法来判断数组是否包含某个对象属性。
一种常见的方法是使用Array.prototype.some()方法。这个方法会遍历数组中的每个元素,并对每个元素执行一个回调函数,如果在回调函数中返回true,则表示数组中包含该对象属性。
例如,我们有一个名为students的数组,每个元素都是一个对象,对象中有属性name和age。现在我们想要判断数组中是否有某个元素的name属性等于"Tom",可以使用some方法来实现:
const students = [
{ name: 'Tom', age: 18 },
{ name: 'Jerry', age: 20 },
{ name: 'Alice', age: 22 }
];
const isNameTom = students.some(student => student.name === 'Tom');
console.log(isNameTom); // 输出 true
另外一种方法是使用Array.prototype.find()方法。这个方法也会遍历数组中的每个元素,并对每个元素执行一个回调函数,但不同的是它返回第一个满足条件的元素而不是返回一个布尔值。
例如,我们想要找到数组中名字为"Tom"的元素,可以使用find方法来实现:
const student = students.find(student => student.name === 'Tom');
console.log(student); // 输出 { name: 'Tom', age: 18 }
如果找不到满足条件的元素,find方法将返回undefined。
以上就是使用ES6判断数组是否包含某个对象属性的两种常见方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)