js如何在数组中查找所有以“时”结尾的字符串的位置
时间: 2024-03-02 08:50:29 浏览: 21
你可以使用 JavaScript 的 `filter()` 方法和字符串的 `endsWith()` 方法来查找所有以“时”结尾的字符串在数组中的位置。下面是一个例子:
```javascript
let myArray = ["早上六时", "下午三时", "晚上十一时", "中午十二点"];
let indexes = myArray.map((str, index) => {
if (str.endsWith("时")) {
return index;
}
}).filter(index => index !== undefined);
console.log(indexes);
```
这将输出:`[0, 1, 2]`,其中包含所有以“时”结尾的字符串在数组中的位置。具体来说,这个例子使用了 `map()` 方法来将所有以“时”结尾的字符串的位置映射到一个新的数组中,然后使用 `filter()` 方法来过滤掉 `undefined` 值。如果想查找所有以“时”结尾的字符串在数组中的元素,可以在 `map()` 方法中返回原始字符串而不是位置。
相关问题
js如何在数组中查找以“时”结尾的字符串的位置
你可以使用 JavaScript 的 `indexOf()` 方法和字符串的 `endsWith()` 方法来查找以“时”结尾的字符串在数组中的位置。下面是一个例子:
```javascript
let myArray = ["早上六时", "下午三时", "晚上十一时", "中午十二点"];
let index = myArray.findIndex(str => str.endsWith("时"));
console.log(index);
```
这将输出:`0`,表示第一个以“时”结尾的字符串是在数组中的第一个元素。如果想查找所有以“时”结尾的字符串在数组中的位置,可以使用循环或 `filter()` 方法来实现。
js如何在数组中查找以“时”结尾的字符串
你可以使用 JavaScript 的 `filter()` 方法和字符串的 `endsWith()` 方法来查找以“时”结尾的字符串。下面是一个例子:
```javascript
let myArray = ["早上六时", "下午三时", "晚上十一时", "中午十二点"];
let result = myArray.filter(str => str.endsWith("时"));
console.log(result);
```
这将输出:`["早上六时", "下午三时", "晚上十一时"]`,其中包含以“时”结尾的字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)