Flex的for和for each区别

本文通过实例对比了JavaScript中for...in与forEach两种循环方式的不同之处。for...in用于遍历对象属性名,而forEach则遍历对象属性值。
之前一直以为它们都是遍历;直到用了hash才知道,它们是有区别的:


var _data:Object=new Object;
_data.key1=value1;
_data.key2=value2;
for (var name:String in _data)
trace(name) // 输出的是key1 key2,即属性名称
for each(var name:String in _data)
trace(name) // 输出的是value1 value2,即属性值

非常好!我们现在来实现一个更高级的众数高亮功能: --- ### ✅ 需求: **如果数据集中有多个众数(即多模态分布,如双众数、三众数等),则每个不同的众数用不同的颜色高亮显示。** 例如: - 数据:`[2, 3, 3, 4, 4, 5]` → 众数是 `3` `4`(都出现两次) - 显示时:`3` 用黄色,`4` 用浅蓝色,其他正常 --- ### ✅ 实现方式 1. 定义一组高亮颜色(如黄、蓝、绿、粉等); 2. 找出所有众数; 3. 给每个众数分配一种颜色; 4. 使用 `<span style="...">` 动态渲染带颜色背景的数字。 --- ### ✅ 更新后的完整代码(支持多色高亮) ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>Mode and Median Calculator</title> <style> body { font-family: Arial, sans-serif; margin: 40px; background-color: #f4f6f9; color: #333; } h1 { text-align: center; color: #2c3e50; } .container { max-width: 800px; margin: 0 auto; padding: 20px; background-color: #fff; border-radius: 10px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); } .controls { display: flex; justify-content: center; align-items: center; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; } button { padding: 10px 15px; font-size: 16px; cursor: pointer; background-color: #3498db; color: white; border: none; border-radius: 5px; transition: background-color 0.3s; } button:hover { background-color: #2980b9; } .data-display { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background-color: #f9f9f9; min-height: 50px; word-break: break-all; line-height: 1.6; } .result { margin-top: 15px; font-weight: bold; color: #27ae60; } </style> </head> <body> <div class="container"> <h1>Mode and Median Calculator</h1> <div class="controls"> <button id="generate">Dataset</button> <div class="size-control"> <button id="decrease">←</button> <span id="size">Size: 10</span> <button id="increase">→</button> </div> <button id="sort">Order Data</button> <button id="showMode">Show Mode</button> <button id="showMedian">Show Median</button> </div> <h3>Data Set:</h3> <div class="data-display" id="dataDisplay"></div> <div class="result" id="result"></div> </div> <script> // Variables let dataSize = 10; let data = []; // DOM Elements const dataDisplay = document.getElementById("dataDisplay"); const resultDiv = document.getElementById("result"); const sizeSpan = document.getElementById("size"); // Color palette for multiple modes const modeColors = [ 'yellow', // First mode 'lightblue', 'lightgreen', 'pink', 'orange', 'lavender', 'cyan' ]; // Update display (plain) function updateDisplay() { dataDisplay.innerHTML = data.map(num => `<span>${num}</span>`).join(", "); resultDiv.textContent = ""; } // Generate dataset: values from 1 to 15 function generateRandomData() { data = Array.from({ length: dataSize }, () => Math.floor(Math.random() * 15) + 1); updateDisplay(); } // Sort data function sortData() { if (data.length === 0) return; data.sort((a, b) => a - b); updateDisplay(); } // Show mode with different color per mode function showMode() { if (data.length === 0) { resultDiv.textContent = "No data."; return; } const frequency = {}; let maxCount = 0; // Count frequencies data.forEach(num => { frequency[num] = (frequency[num] || 0) + 1; if (frequency[num] > maxCount) maxCount = frequency[num]; }); // Get modes as numbers const modes = Object.keys(frequency) .filter(key => frequency[key] === maxCount) .map(Number); // Check if there's no mode (all appear once or uniform distribution) const uniqueValues = Object.keys(frequency).length; if ((maxCount === 1 && uniqueValues > 1) || (modes.length === uniqueValues && uniqueValues > 1)) { resultDiv.textContent = "There is no mode"; updateDisplay(); return; } // Map each mode to a color const colorMap = {}; modes.forEach((mode, index) => { colorMap[mode] = modeColors[index % modeColors.length]; // Cycle through colors }); // Render data with colored highlights for each mode dataDisplay.innerHTML = data.map(num => { const bgColor = colorMap[num]; return bgColor ? `<span style="background-color: ${bgColor}; padding: 2px 4px; border-radius: 3px; font-weight: bold;">${num}</span>` : `<span>${num}</span>`; }).join(", "); resultDiv.textContent = `Mode(s): ${modes.join(", ")}`; } // Calculate median function calculateMedian() { if (data.length === 0) return "No data"; const sorted = [...data].sort((a, b) => a - b); const mid = Math.floor(sorted.length / 2); return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid]; } // Event Listeners document.getElementById("generate").addEventListener("click", generateRandomData); document.getElementById("increase").addEventListener("click", () => { dataSize++; sizeSpan.textContent = `Size: ${dataSize}`; generateRandomData(); }); document.getElementById("decrease").addEventListener("click", () => { if (dataSize > 1) { dataSize--; sizeSpan.textContent = `Size: ${dataSize}`; generateRandomData(); } }); document.getElementById("sort").addEventListener("click", sortData); document.getElementById("showMode").addEventListener("click", showMode); document.getElementById("showMedian").addEventListener("click", () => { const median = calculateMedian(); resultDiv.textContent = `Median: ${median}`; updateDisplay(); // Remove all highlights }); // Initialize on load generateRandomData(); </script> </body> </html> ``` --- ### 🔍 关键点解释 | 特性 | 如何实现 | |------|----------| | **多种高亮颜色** | 定义 `modeColors` 数组,为每个众数按顺序分配颜色 | | **颜色映射表** | 使用 `colorMap` 对象记录 `数值 → 颜色` 的对应关系 | | **动态样式插入** | 在 `.map()` 中使用内联 `style="..."` 给众数加背景色 | | **无众数判断** | 当所有值频率相同且不止一个唯一值时,显示 “There is no mode” | | **清晰可读性** | 每个众数颜色不同,便于区分多模态情况 | --- ✅ 示例输出: - 数据:`[3, 3, 5, 5, 7]` - 众数:`3`, `5`(各出现 2 次) - `3` → 黄色,`5` → 浅蓝 - 结果栏显示:`Mode(s): 3, 5` --- 🎯 提示: 你可以扩展此功能: - 添加图例说明哪种颜色代表哪个数; - 或点击众数弹出详情; - 或让用户自定义颜色主题。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值