javascript - 将括号添加到字符串数组中的最小和最大数字

标签 javascript html jquery

此代码将为数组中的每个索引创建一个 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

这是我尝试过的:

我尝试了这段代码,将数字和字母分成两个不同的数组,这样我就可以将最大值和最小值应用于数字

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>

关于javascript - 将括号添加到字符串数组中的最小和最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67240962/

相关文章:

javascript - 没有找到数据时, Angular js : value set to 0 for all scopes,

javascript - Bootstrap 弹出链接不起作用

带部分边框的 HTML5/CSS3 圆形

Jquery滚动顶部触发两点之间的函数?

javascript - Angular bootstrap datepicker 开始日期函数

javascript - console.log 无法获取端口变量,我已经提供了屏幕截图

javascript - 根据选定的单选按钮显示多个字段集之一

javascript - React Native 中的 redux-form 有问题

javascript - 缩放 HTML Canvas 元素

javascript - jQuery ID 以