我对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',
'brown'
]我想替换第一个数组中没有/([0-9]+):([0-9]+)/g格式、第二个数组中找不到的值。因此,第一个数组中的所有"blah“和”未定义“都应该替换为johnson,但是与第二个数组和#:#数字匹配的名称仍然保留,因此输出显示:
[
'1:1', 'johnson',
'1:2', 'johnson',
'1:3', 'smith',
'1:4', 'johnson',
'1:5', 'williams',
'1:6', 'johnson',
'1:7', 'johnson',
]发布于 2021-01-19 20:37:16
我们可以在一个if循环中使用一个简单的for语句来实现您想要的结果。
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); 发布于 2021-01-19 20:37:47
让我们调用主数组arr和名称names数组,然后这样做就可以了:
arr.map(item => !/([0-9]+):([0-9]+)/g.test(item) && !names.includes(item) ? 'johnson' : item)发布于 2021-01-19 20:41:13
我推荐一种使用数组的map()函数的功能方法。或者可以使用filter(),但是由于您想替换某些条目,所以映射用更少的步骤来完成它。
Array.prototype.map()方法接受将对数组中的每个项调用的函数,该函数的返回将在返回的索引中进行。
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);https://stackoverflow.com/questions/65798912
复制相似问题