我想返回一个带有特定单词的字符串数组。例如,如果我想要所有带松鼠字的字符串,该怎么办?
输入
[“蓝松鼠”,“粉红色马”,“黄松鼠”,“绿猫”,“白蛙”,“黑狮”,“橙松鼠”]
返回
[“蓝色松鼠”,“黄色松鼠”,“橙色松鼠”]
我的代码:
function iJustWantSquirrel (animals) {
const onlySquirrels = animals.filter(function(animal) {
if (animal.length == 'Squirrel') {
return animal;
}
});
return onlySquirrels;
}
答案 0 :(得分:1)
您需要查找字符串是否包含可以使用includes
方法执行的单词。同样,当您使用过滤器时,回调函数仅需要返回一个布尔值,而不是要返回的实际值
const data = [ 'Blue Squirrel', 'Pink Horse', 'Yellow Squirrel', 'Green Cat', 'White Frog', 'Black Lion', 'Orange Squirrel' ]
function iJustWantSquirrel (animals) {
const onlySquirrels = animals.filter(function(animal) {
return animal.toLowerCase().includes('squirrel')
});
return onlySquirrels;
}
console.log(iJustWantSquirrel(data));
答案 1 :(得分:1)
您可以过滤掉不需要的元素,如下所示:
import QtQuick 2.7
Item {
id: textBox
clip: true
property alias inputText: inputText.text
property alias mode: inputText.echoMode
property color borderColor: "gray"
property int borderWidth: 1
activeFocusOnTab: true // <--
onActiveFocusChanged: if(activeFocus) inputText.focus = true // <--
Rectangle {
id: rectInput
anchors.fill: parent
border.color: borderColor
border.width: borderWidth
radius: 4
}
TextInput {
id: inputText
anchors.fill: parent
anchors.leftMargin: 3
verticalAlignment: Text.AlignVCenter
selectByMouse: true
focus: true // <--
}
}
这将返回:
const array = [
'Blue Squirrel',
'Pink Horse',
'Yellow Squirrel',
'Green Cat',
'White Frog',
'Black Lion',
'Orange Squirrel'
];
const result = array.filter(s => s.toLowerCase().indexOf('squirrel') >= 0);
答案 2 :(得分:0)
只需稍微更改一下代码片段即可检查字符串中是否存在“松鼠”一词。
function iJustWantSquirrel (animals) {
const onlySquirrels = animals.filter((animal) => {
if (animal.includes('Squirrel')) {
return animal;
}
});
return onlySquirrels;
}
const animalArray = [ 'Blue Squirrel', 'Pink Horse', 'Yellow Squirrel', 'Green Cat', 'White Frog', 'Black Lion', 'Orange Squirrel' ];
const newAnimalArray = iJustWantSquirrel(animalArray);
alert(JSON.stringify(newAnimalArray));