我正在尝试遍历一个数组并将其中的字符串与另一个字符串进行比较,并将它们添加到一个新数组中。
var adUnitMacro = 'news'
var verticalOutput = []
keywordArray = ['news', 'homepage', 'technology', 'entertainment', 'sport',
'business', 'lifestyle', 'travel', 'motoring', 'property'
]
for (i = 0; i < keywordArray.length; i++) {
if (keywordArray[i] === adUnitMacro) {
verticalOutput.push(keywordArray[i]);
}
}
console.log(verticalOutput)
console.log(keywordArray[0])
在此示例中,'news'被添加到verticalOutput数组中。但是,如果adUnitMacro变量是'123news123',则不会将任何内容添加到verticalOutput数组,因为关键字数组中的'news'不是完全匹配。
如果adUnitMacro中存在关键字数组中的字符串,那么我怎么能这样做?这些值会被推送到verticalOutput数组?
例如adUnitMacro = 'newshomepagetechnology'
verticalOutput
数组为['news', 'homepage', 'technology']
答案 0 :(得分:2)
尝试将keywordArray[i] === adUnitMacro
更改为adUnitMacro.includes(keywordArray[i])
。
您的代码最终会如下所示:
var adUnitMacro = 'news'
var verticalOutput = []
keywordArray = ['news', 'homepage', 'technology', 'entertainment', 'sport',
'business', 'lifestyle', 'travel', 'motoring', 'property'
]
for (i = 0; i < keywordArray.length; i++) {
if (adUnitMacro.includes(keywordArray[i])) {
verticalOutput.push(keywordArray[i]);
}
}
答案 1 :(得分:0)
var adUnitMacro = 'newshomepagetechnology'
var verticalOutput = []
keywordArray = ['news', 'homepage', 'technology', 'entertainment', 'sport',
'business', 'lifestyle', 'travel', 'motoring', 'property'
]
for (i = 0; i < keywordArray.length; i++) {
if (adUnitMacro.includes(keywordArray[i])) {
verticalOutput.push(keywordArray[i]);
}
}
console.log(verticalOutput)
console.log(keywordArray[0])