首页 > 解决方案 > 将括号添加到字符串数组中的最小和最大数字

问题描述

此代码将为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

标签: javascripthtmljquery

解决方案


这是你想要的吗?您只是忘记获取 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>


推荐阅读