【发布时间】:2021-04-24 08:56:20
【问题描述】:
此代码将为数组中的每个索引创建一个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[index]}而不是在text中使用整个数组${getWords} -
为什么不使用有序列表
<ol>和<li>? -
@NinaScholz 是的,我刚刚意识到我可以使用
olxD
标签: javascript html jquery