为什么将我的函数应用到数组后 returns 是同一个数组?
why after applying my function to the array it returns the same array?
我正在用我的函数 compare 遍历数组以从数组中获取最大温度数,但是在将函数应用于数组温度后没有任何变化。
let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];
function compare(temperature) {
let i = 0;
for (i = 0; i < temperature.length; i++) {
if (typeof temperature[i] === "string") temperature.splice(i, 1);
}
for (let k = i + 1; k < temperature.length; k++) {
if (temperature[i] < temperature[k]) Array.splice(i, 1);
else if (temperature[i] > temperature[k]) Array.splice(k, 1);
}
return temperature;
}
console.log(temperature);
看看这个!
let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];
function compare(temperature) {
let i = 0;
for (i = 0; i < temperature.length; i++) {
if (typeof temperature[i] === "string")
temperature.splice(i, 1);
}
for (let k = i + 1; k < temperature.length; k++) {
if (temperature[i] < temperature[k])
Array.splice(i, 1);
else if (temperature[i] > temperature[k])
Array.splice(k, 1);
}
return temperature;
}
console.log(compare(temperature));
您可以通过在数组上使用 Math.max()
来使用一行代码实现此目的。
工作演示:
// Input array
let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];
// Math.max() to get maximum number element from an array.
const maxTemp = Math.max(...temperature.filter(elem => typeof elem !== 'string'));
// Result
console.log(maxTemp);
我正在用我的函数 compare 遍历数组以从数组中获取最大温度数,但是在将函数应用于数组温度后没有任何变化。
let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];
function compare(temperature) {
let i = 0;
for (i = 0; i < temperature.length; i++) {
if (typeof temperature[i] === "string") temperature.splice(i, 1);
}
for (let k = i + 1; k < temperature.length; k++) {
if (temperature[i] < temperature[k]) Array.splice(i, 1);
else if (temperature[i] > temperature[k]) Array.splice(k, 1);
}
return temperature;
}
console.log(temperature);
看看这个!
let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];
function compare(temperature) {
let i = 0;
for (i = 0; i < temperature.length; i++) {
if (typeof temperature[i] === "string")
temperature.splice(i, 1);
}
for (let k = i + 1; k < temperature.length; k++) {
if (temperature[i] < temperature[k])
Array.splice(i, 1);
else if (temperature[i] > temperature[k])
Array.splice(k, 1);
}
return temperature;
}
console.log(compare(temperature));
您可以通过在数组上使用 Math.max()
来使用一行代码实现此目的。
工作演示:
// Input array
let temperature = [1, 2, 3, 4, 5, 6, 7, 8, 9, "error"];
// Math.max() to get maximum number element from an array.
const maxTemp = Math.max(...temperature.filter(elem => typeof elem !== 'string'));
// Result
console.log(maxTemp);