javascript - 将括号添加到字符串数组中的最小和最大数字
问题描述
此代码将为p
数组中的每个索引创建一个元素,并将括号放在数组中的最低和最高数字上
const liArray = [5.6, 8.7, 1.3, 10, 56];
const min = Math.min.apply(Math, liArray);
const max = Math.max.apply(Math, liArray);
const parentElement = document.getElementById("myDiv");
liArray.forEach((currentValue, index) => {
const elm = document.createElement('p');
let text = `${index + 1}. ${(currentValue == min || currentValue == max) ? `(${currentValue})` : currentValue}`;
elm.innerText = text;
parentElement.appendChild(elm);
});
<div id="myDiv"></div>
但我的数组是这样的
const liArray = ["5.6 hello", "8.7 hi", "1.3 hey", "10 hi", "56 hello"]
我还想在最低和最高数字上添加括号并像这样输出
1. 5.6 hello
2. 8.7 hi
3. (1.3) hey
4. 10 hi
5. (56) hello
这是我尝试过的:
我试过这段代码将数字和字母分成2个不同的数组,这样我就可以将最大值和最小值应用于数字
const liArray = ["5.6 hello", "8.7 hi", "1.3 hey", "10 hi", "56 hello"];
const parentElement = document.getElementById("myDiv");
const getNumbers = liArray.map((i) => Number(i.replace(/[^0-9.]/g, "")));
const getWords = liArray.map((i) => i.replace(/[0-9.]/g, ""));
const min = Math.min.apply(Math, getNumbers);
const max = Math.max.apply(Math, getNumbers);
getNumbers.forEach((currentValue, index) => {
const elm = document.createElement('p');
let text = `${index + 1}. ${(currentValue == min || currentValue == max) ?
`(${currentValue})` : currentValue}. ${getWords}`;
elm.innerText = text;
parentElement.appendChild(elm);
});
但它改为输出这个
2. 8.7. hello, hi, hey, hi, hello
3. (1.3). hello, hi, hey, hi, hello
4. 10. hello, hi, hey, hi, hello
5. (56). hello, hi, hey, hi, hello
解决方案
这是你想要的吗?您只是忘记获取 getwords 数组的元素。
const liArray = ["5.6 hello", "8.7 hi", "1.3 hey", "10 hi", "56 hello"];
const parentElement = document.getElementById("myDiv");
const getNumbers = liArray.map((i) => Number(i.replace(/[^0-9.]/g, "")));
const getWords = liArray.map((i) => i.replace(/[0-9.]/g, ""));
const min = Math.min.apply(Math, getNumbers);
const max = Math.max.apply(Math, getNumbers);
getNumbers.forEach((currentValue, index) => {
const elm = document.createElement('p');
let text = `${index + 1}. ${(currentValue == min || currentValue == max) ?
`(${currentValue})` : currentValue}. ${getWords[index]}`;
elm.innerText = text;
parentElement.appendChild(elm);
});
<div id="myDiv"></div>
推荐阅读
- angular - 在Angular中对表格行进行排序
- c# - 使用 asp 面板在客户端上隐藏/显示 html 块有效,但我无法更新块中的文本框
- c# - BeginAcceptTcpClient 线程安全吗?C#
- javascript - 在对象数组中搜索对象
- javascript - 试图让 nerdamer 在 React Native 项目中工作
- java - 在 Internet Explorer 11 中运行 Java
- sql - 我试图理解这串代码和它在说什么,特别是这个'[^|]+'
- python - 在大型数据集中检索多个查找值?
- r - 如何将 RGL/CAR scatter3d 图显示为轨迹线
- batch-file - 如何使用 CMD 打开控制面板的系统信息