简体   繁体   English

Javascript - 使用索引替换数组中的多个元素

[英]Javascript - Replace multiple elements in an array using index

Consider following array in Javascript:考虑以下 Javascript 数组:

var array1 = ['S', 'T', 'A', 'C', 'K', 'O', 'V', 'E', 'R', 'F', 'L', 'O', 'W'];

Now I want to replace all the elements at once from index 3 to 9 in following way:现在我想通过以下方式一次替换索引 3 到 9 中的所有元素:

array1 = ['S', 'T', 'A', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'L', 'O', 'W'];

Is it possible to achieve in javascript ?是否可以在 javascript 中实现?

Note : I want to perform following operation using array only注意:我只想使用数组执行以下操作

Use Array.fill()使用Array.fill()

 var array1 = ['S', 'T', 'A', 'C', 'K', 'O', 'V', 'E', 'R', 'F', 'L', 'O', 'W']; array1.fill('X', 3, 10) console.log(array1)

Use array splice() method使用数组 splice() 方法

 var array1= ['S', 'T', 'A', 'C', 'K', 'O', 'V', 'E', 'R', 'F', 'L', 'O', 'W']; // At position 3, delete 7 and add 7 elements: array1.splice(3, 7, "X","X","X","X","X","X","X"); console.log(array1);

One way is with Array.prototype.map :一种方法是使用Array.prototype.map

This loops through every index of the array, and if the index is between 3 and 9 (inclusive), set it to 'X', otherwise keep it as the original chr (character)这会循环遍历数组的每个索引,如果索引在 3 到 9(含)之间,则将其设置为 'X',否则将其保留为原始 chr(字符)

 var array1 = ['S', 'T', 'A', 'C', 'K', 'O', 'V', 'E', 'R', 'F', 'L', 'O', 'W']; var array2 = array1.map((chr, idx) => 3 <= idx && idx <= 9 ? 'X' : chr); console.log(array2);

It sure does.确实如此。

const arr = ['a', 'b', 'c', 'd', 'e']

function replaceWithX(start, end) {
  for (let i = start; i <= end; i++) {
    arr[i] = 'x'
  }
}

replaceWithX(1, 3)

console.log(arr) // ["a", "x", "x", "x", "e"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Javascript 根据条件/索引替换内部数组的元素? - How to replace elements of an inner array on condition/index basis using Javascript? 在javascript中使用regex和replace()替换数组元素 - Replacing array elements using regex and replace() in javascript 使用数组元素进行搜索并使用javascript替换所有内容? - Using array elements to do a search and replace all using javascript? 如何使用第二个数组元素查找数组中多个元素的索引,然后使用结果匹配第三个数组的索引(Javascript) - How to find indexes of multiple elements in array with second array elements and then use result to match index of third array (Javascript) 用JavaScript中的.splice()替换多个元素 - replace multiple elements with .splice() in javascript 替换数组javascript中的备用元素 - replace alternate elements in array javascript 使用 Javascript 替换现有文件并推送到数组的顶部索引 - Replace existing file and push to top index of array using Javascript 使用一个数组的元素创建新数组作为索引,以选择不同数组中的元素 - JavaScript - Create new array using elements of one array as an index to select elements in a different array - JavaScript 如果元素在 javascript 中具有特定的 Xyz 前缀,如何用索引值替换数组中的元素列表 - how to replace list of elements in an array with index value, if element has specific prefix of Xyz in javascript 使用javascript替换链接中的元素 - Replace elements in a link using javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM