javascript - 如何使用同一数组中的其他项目更改数组中的项目

标签 javascript arrays

我需要将数组 A 更改为类似于数组 B,确保散列项成为任意数量的非散列项之前,直到下一个散列项

const A = [ '# test',
  'test',
  '# layouts',
  'main',
  'nav' ]

const B = ['test/test',
    'layouts/main',
    'layouts/nav' ]

最佳答案

您可以使用reduce来实现此目的,累加器应该是一个包含两个值的对象,第一个是结果数组,另一个是要在中使用的当前哈希字符串reduce 生成路径。一旦reduce完成工作,我们就可以将累加器的result属性存储到我们的结果变量B中:

const B = A.reduce((acc, str) => {                           // for each string in the array A
   if(str.indexOf("#") === 0) {                              // if the string is hashed one
      acc.currentHash = str.slice(2);                        // set the current hash to this string
   } else {                                                  // otherwise
      acc.result.push(acc.currentHash + "/" + str);          // use the current hash to generate the resulting string of the current string
   }
   return acc;
}, { result: [], currentHash: ""}).result;                   // once reduce finishes, use '.result' to access the result array of the accumulator

示例:

const A = [ '# test', 'test', '# layouts', 'main', 'nav' ];

const B = A.reduce((acc, str) => {
   if(str.indexOf("#") === 0) {
      acc.currentHash = str.slice(2);
   } else {
      acc.result.push(acc.currentHash + "/" + str);
   }
   return acc;
}, { result: [], currentHash: ""}).result;

console.log(B);

关于javascript - 如何使用同一数组中的其他项目更改数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53732337/

相关文章:

javascript - 与文件 uploader 一起使用时如何在底部对齐按钮并且在顶部对齐标签?

javascript - Backbone.js 集合集合

c - 为什么需要在链表中存储下一项指针

c# - c#中的List数组

c++ - 应为常量表达式,无法分配常量大小为 0 的数组

php - Mysql将数据存储在数组中然后对desc进行排序

c# - 如何在不使用循环的情况下修剪字符串数组中的每个字符串元素?

javascript - 将 lat 长字符串转换为谷歌地图 API LatLng 对象

javascript - 在值更改时调用自定义方法

javascript - 传单在多边形中绘制点并添加到可编辑图层