我真的需要你的帮助
如何在javascript中搜索用户输入的数组?
以下是数组脚本:
var items = [
["0001", "Roman", "Reading"],
["0002", "Ryan", Playing the Guitar "],
["0003", "Wiley", "Cooking"],
["0004", "Jack", "Gardening"]
]
能否给我一些html和javascript脚本的示例。感谢您的帮助。
答案 0 :(得分:-1)
通常,这种搜索是使用对象进行的,但是由于您已经给了我们一个数组,所以该函数从数组中搜索结果。
首先,我们需要一个过滤字符串。然后,我们遍历数组并检查string是否包含过滤器字符串。如果包含它,我们将结果推送到结果数组。
JS
var items = [
["0001", "Roman", "Reading"],
["0002", "Ryan", "Playing the Guitar"],
["0003", "Wiley", "Cooking"],
["0004", "Jack", "Gardening"]
];
function handleSearch() {
var value = document.getElementById('searchValue').value;
var results = [];
if (value) {
items.forEach(item => {
item.forEach(itemString => {
if (itemString.toLowerCase().includes(value.toLowerCase())) {
results.push(`${value} found in ${itemString} in block ${item}`);
};
});
});
console.log(results);
}
}
HTML
<input id="searchValue"/>
<button onclick="handleSearch()">Search</button>
答案 1 :(得分:-1)
这是一个脚本,它将输出父数组内子数组的索引:
Object.defineProperty(Object.prototype, "equals", {
"value": function(target) {
let sourceProperties = Object.getOwnPropertyNames(this);
let targetProperties = Object.getOwnPropertyNames(target);
let comparer = function(value, index, source) {
return this[value] === target[value];
};
if(sourceProperties.length === targetProperties.length)
return sourceProperties.every(comparer, this);
else
return false;
}
});
Object.defineProperty(Array.prototype, "findObject", {
"value": function(objectToFind) {
let comparer = function(value, index, source) {
return value.equals(objectToFind);
};
return this.findIndex(comparer);
}
});
let items = [
["0001", "Roman", "Reading"],
["0002", "Ryan", "Playing the Guitar"],
["0003", "Wiley", "Cooking"],
["0004", "Jack", "Gardening"]
];
console.log(items.findObject(["0002", "Ryan", "Playing the Guitar"]));
答案 2 :(得分:-1)
首先,将id设置为输入标签,并将'onkeyup'事件设置为JS函数。
<input id="searchInput" onkeyup="Search()">
在JS中,获取使用getElementById输入的输入。使用filter方法,过滤items数组。使用toLowerCase()忽略输入的大小写。
var items = [
["0001", "Roman", "Reading"],
["0002", "Ryan", "Playing the Guitar "],
["0003", "Wiley", "Cooking"],
["0004", "Jack", "Gardening"]
]
function Search(){
var input = document.getElementById("searchInput").value.toLowerCase();
var filteredArray = items.filter(x=> x[1].toLowerCase().includes(input));
console.log(filteredArray); //will display the filtered array according to the user input
}