朋友們。我想要一個函式,當我給它陣列時,該函式將從這些陣列中分離出正數和負數并將它們推送到負數或正數。
但正如您在下面看到的,我可以為 arrayOne 做到這一點。如果我想用arrayTwo 來做,我必須再次復制所有代碼。有什么辦法,我創建一個函式,并將該函式用于所有陣列?
例如 checkValue(arrayOne)、checkValue(arrayTwo) 等。
先感謝您!
const negativeNumbers = []
const positiveNumbers = []
const arrayOne = [-2, 5, -3, 6]
const arrayTwo = [-12, 15, -13, 16]
const checkValue = arrayOne.forEach((element) => {
if (element<0){
negativeNumbers.push(element)
}
if (element>=0) {
positiveNumbers.push(element)
}
})
console.log(positiveNumbers)
console.log(negativeNumbers)
uj5u.com熱心網友回復:
您可以將其轉換為接受陣列并以[array, array]or的形式回傳兩個陣列的函式{arr1: array, arr2: array}
const arrayOne = [-2, 5, -3, 6]
const arrayTwo = [-12, 15, -13, 16]
function split_by_sign(arr) {
const negativeNumbers = []
const positiveNumbers = []
arr.forEach((element) => {
if (element < 0) {
negativeNumbers.push(element)
}
if (element >= 0) {
positiveNumbers.push(element)
}
// btw, what about zero?
})
return [positiveNumbers, negativeNumbers]
}
console.log("arrayOne splitted: ", split_by_sign(arrayOne))
console.log("arrayTwo splitted: ", split_by_sign(arrayTwo))
// or practical usage:
var [positive, negative] = split_by_sign(arrayOne)
console.log("positive of array1: " positive)
console.log("negative of array1: " negative)
uj5u.com熱心網友回復:
這是使用Array#filter的@ITgodman 答案的更簡單版本。
function splitNegativePositive(array){
return {
positives: array.filter(n => n >= 0),
negatives: array.filter(n => n < 0),
}
}
const input1 = [-1, 5, 9, 0, -3];
const input2 = [-10, -5, 7, 0, 3];
console.log({
input1,
input1Output: splitNegativePositive(input1),
input2,
input2Output: splitNegativePositive(input2),
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/531008.html
上一篇:我無法向動態陣列添加新元素
