Javascript 替换数组中不带';t将另一数组中的任何项与特定值匹配
我对Javascript还是很陌生,在数组循环和替换项方面遇到了麻烦。我希望这个解释是清楚的 我有一个如下所示的数组:Javascript 替换数组中不带';t将另一数组中的任何项与特定值匹配,javascript,arrays,replace,Javascript,Arrays,Replace,我对Javascript还是很陌生,在数组循环和替换项方面遇到了麻烦。我希望这个解释是清楚的 我有一个如下所示的数组: [ '1:1', 'blah', '1:2', undefined, '1:3', 'smith', '1:4', 'blah', '1:5', 'williams', '1:6', 'blah', '1:7', 'blah' ] [ 'taylor', 'smith', 'williams',
[
'1:1', 'blah',
'1:2', undefined,
'1:3', 'smith',
'1:4', 'blah',
'1:5', 'williams',
'1:6', 'blah',
'1:7', 'blah'
]
[
'taylor',
'smith',
'williams',
'brown'
]
我还有另一个数组,看起来像这样:
[
'1:1', 'blah',
'1:2', undefined,
'1:3', 'smith',
'1:4', 'blah',
'1:5', 'williams',
'1:6', 'blah',
'1:7', 'blah'
]
[
'taylor',
'smith',
'williams',
'brown'
]
我要替换第一个数组中不在/([0-9]+):([0-9]+)/g
格式且在第二个数组中找不到的任何值。因此,第一个数组中的所有“blah”和“undefined”都应该替换为johnson
,但与第二个数组和#::#数字匹配的名称仍然保留,因此输出显示:
[
'1:1', 'johnson',
'1:2', 'johnson',
'1:3', 'smith',
'1:4', 'johnson',
'1:5', 'williams',
'1:6', 'johnson',
'1:7', 'johnson',
]
我们可以在
for
循环中使用一个简单的if
语句来实现您想要的
var originalArray=[
“1:1”,“诸如此类”,
“1:2”,未定义,
“1:3”,“史密斯”,
“1:4”,“诸如此类”,
“1:5”,“威廉姆斯”,
“1:6”,“诸如此类”,
“1:7”,“诸如此类”
];
var matchArray=[
“泰勒”,
“史密斯”,
“威廉姆斯”,
“棕色”
];
对于(变量i=0;i
让我们调用主数组arr
和名称数组names
,然后这应该可以实现以下功能:
arr.map(item=>!/([0-9]+):([0-9]+)/g.test(item)&&&&!name.includes(item)?“johnson”:item)
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);
到目前为止,你尝试了什么?我认为你需要考虑原始数组可以包含未定义的值,当将字符串匹配到正则表达式时,应该使用Value.Read而不是测试。或者只需检查数组值不是字符串并跳过它,就应该执行ITVAdItMatthChrEx=Value.Test[//([09] +):([09+])/g;TypeError:value.test不是一个函数我接受了编辑,请再试一次并告诉我们它是否有效!没用。所有内容仍保留其原始值。map返回一个副本,因此如果要更改原始数组的值,则应使用它替换原始数组,例如:
arr=arr.map(item=>!/([0-9]+):([0-9]+)/g.test(item)&&&&!names.includes(item);“johnson”:item)