我对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”和“ undefined”都应替换为,johnson
但与第二个数组和#:#数字匹配的名称仍然保留,因此输出显示:
[
'1:1', 'johnson',
'1:2', 'johnson',
'1:3', 'smith',
'1:4', 'johnson',
'1:5', 'williams',
'1:6', 'johnson',
'1:7', 'johnson',
]
我们可以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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句