js编写程序,找出指定元素“y”在数组['a','b','y','a','y','y']出现的所有位置
时间: 2024-01-27 20:06:33 浏览: 35
以下是两种JavaScript编写程序,找出指定元素在数组中出现的所有位置的例子:
1.使用forEach()方法和push()方法
```javascript
function findAllOccurrences(arr, target) {
var temp = [];
arr.forEach(function(val, index) {
val !== target || temp.push(index);
});
return temp;
}
console.log(findAllOccurrences(['a', 'b', 'y', 'a', 'y', 'y'], 'y')); // 输出:[2, 4, 5]
```
2.使用indexOf()方法和while循环
```javascript
function findall(a, x) {
var results = [],
len = a.length,
pos = 0;
while (pos < len) {
pos = a.indexOf(x, pos);
if (pos === -1) {
break;
}
results.push(pos);
pos += 1;
}
return results;
}
console.log(findall(['a', 'b', 'y', 'a', 'y', 'y'], 'y')); // 输出:[2, 4, 5]
```
相关问题
js在指定位置修改数组元素
你可以使用数组索引来修改数组元素。例如,如果你想要将数组中第三个元素修改为 "hello",你可以使用以下代码:
```
var arr = ["apple", "banana", "orange"];
arr[2] = "hello";
console.log(arr); // Output: ["apple", "banana", "hello"]
```
这会将数组中索引为 2 的元素(即第三个元素)修改为 "hello"。你可以将任何索引值替换为你想要的值。
js中在数组指定位置插入元素
在 JavaScript 中,可以使用 `splice()` 方法在指定位置插入元素。`splice()` 方法接受三个参数:起始索引、要删除的元素数和要添加的新元素。如果要在指定位置插入元素,则只需将第二个参数设置为 0,第三个参数设置为要添加的元素,如下所示:
```javascript
const array = [1, 2, 3, 4, 5];
array.splice(2, 0, 6); // 在索引为2的位置插入元素6
console.log(array); // [1, 2, 6, 3, 4, 5]
```
在上面的例子中,我们将元素 6 插入了索引为 2 的位置,此时数组变为 `[1, 2, 6, 3, 4, 5]`。
相关推荐
![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_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)