写一个JavaScript查询水果案例
时间: 2024-05-11 20:17:21 浏览: 86
好的,以下是一个简单的JavaScript查询水果的案例:
HTML代码:
```html
<label for="fruitInput">请输入水果名称:</label>
<input type="text" id="fruitInput">
<button onclick="searchFruit()">查询</button>
<p id="result"></p>
```
JavaScript代码:
```javascript
const fruits = [
{ name: "苹果", price: 5 },
{ name: "香蕉", price: 3 },
{ name: "橙子", price: 4 },
{ name: "西瓜", price: 10 },
{ name: "菠萝", price: 6 }
];
function searchFruit() {
const input = document.getElementById("fruitInput").value;
const result = document.getElementById("result");
const fruit = fruits.find(f => f.name === input);
if (fruit) {
result.textContent = `您查询的${input}的价格为${fruit.price}元。`;
} else {
result.textContent = `很抱歉,我们没有找到您查询的${input}。`;
}
}
```
这个案例中,我们定义了一个包含水果名称和价格的数组,然后通过用户输入的水果名称来查询相应的价格。我们使用了`Array.find()`方法来查找输入的水果是否在数组中存在,如果存在,就显示其价格,否则显示未找到的提示。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)