首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用特定值替换数组中与另一个数组中的任何项不匹配的项

用特定值替换数组中与另一个数组中的任何项不匹配的项
EN

Stack Overflow用户
提问于 2021-01-19 20:21:12
回答 3查看 440关注 0票数 1

我对Javascript还是很陌生的,我在遍历数组和替换条目方面遇到了困难。我希望这个解释是清楚的。

我有一个看起来像这样的数组:

代码语言:javascript
运行
复制
[
  '1:1',   'blah',
  '1:2',   undefined,
  '1:3',   'smith',
  '1:4',   'blah',
  '1:5',   'williams',
  '1:6',   'blah',
  '1:7',   'blah'
]

我有另一个数组看起来是这样的:

代码语言:javascript
运行
复制
[ 
   'taylor', 
   'smith', 
   'williams', 
   'brown'
]

我想替换第一个数组中没有/([0-9]+):([0-9]+)/g格式、第二个数组中找不到的值。因此,第一个数组中的所有"blah“和”未定义“都应该替换为johnson,但是与第二个数组和#:#数字匹配的名称仍然保留,因此输出显示:

代码语言:javascript
运行
复制
[
  '1:1',   'johnson',
  '1:2',   'johnson',
  '1:3',   'smith',
  '1:4',   'johnson',
  '1:5',   'williams',
  '1:6',   'johnson',
  '1:7',   'johnson',
]
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-01-19 20:37:16

我们可以在一个if循环中使用一个简单的for语句来实现您想要的结果。

代码语言:javascript
运行
复制
var originalArray = [
  '1:1',   'blah',
  '1:2',   undefined,
  '1:3',   'smith',
  '1:4',   'blah',
  '1:5',   'williams',
  '1:6',   'blah',
  '1:7',   'blah'
];

var matchArray = [ 
   'taylor', 
   'smith', 
   'williams', 
   'brown'
];

for (var i = 0; i < originalArray.length; i++) {
    var value = originalArray[i];
    //Check if it matches your RegEx
    if (value !== undefined) {
      var doesItMatchRegEx = value.match(/([0-9]+):([0-9]+)/g);
    } else {
      originalArray[i] = "johnson";
    }
    //Check if it is in your second array
    var isItInSecondArray = matchArray.includes(value);
    if (!doesItMatchRegEx && !isItInSecondArray) {
        //Let's replace it with Johnson
        originalArray[i] = "johnson";
    }
}

console.log(originalArray);    
票数 1
EN

Stack Overflow用户

发布于 2021-01-19 20:37:47

让我们调用主数组arr和名称names数组,然后这样做就可以了:

  • arr.map(item => !/([0-9]+):([0-9]+)/g.test(item) && !names.includes(item) ? 'johnson' : item)
票数 0
EN

Stack Overflow用户

发布于 2021-01-19 20:41:13

我推荐一种使用数组的map()函数的功能方法。或者可以使用filter(),但是由于您想替换某些条目,所以映射用更少的步骤来完成它。

Array.prototype.map()方法接受将对数组中的每个项调用的函数,该函数的返回将在返回的索引中进行。

代码语言:javascript
运行
复制
validNames = [‘taylor’...];
numberFormatRegex = /([0-9]+):([0-9]+)/g;

// This function will run on each value in the array, and the RETURN becomes the new value in the array created after mapping
mapFunction = (value) => {
  if(!validNames.includes(value) && !numberFormatRegex.test(value)){
    // only values NOT in the validNames list AND (&&) NOT passing the refer will enter this branch 
    
    return ‘Johnson’;
  }
  // This only runs if the previous return didn’t so it will only happen for valid values

}

// Call map() method with our new function and save result to new array
// note that the inputArray will be unchanged and a new one will be returned and assigned to newArray
newArray = inputArray.map(mapFunction);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65798912

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档