function question4(angka){
var w=0 , jml=0, rtt=0;
var nilai;
nilai=angka;
for(w=0;w < nilai.length;w )
{
jml=jml nilai[w];
}
rtt=jml/nilai.length;
console.log(rtt);
}
console.log(question4([4, 5, 6, 7, 8]));
console.log(question4([100, 200, 300, 400, 500]));
console.log(question4([-1, 4, 7, 11]));
If there is one or more array elements with negative values, then the function is direct outputs the text 'Negative!'.
CodePudding user response:
First of all you don't have to call the question4()
within a console.log()
because the question4()
doesn't return
anything, instead check in the loop if (nilai[w] < 0) console.log('Negative!')
CodePudding user response:
it is so easy, question4 function must return a value..
function question4(angka){
for(w=0;w < angka.length;w )
{
if(angka[w]<0)
{
return "Negative";
}
}
return "Posetive";
}
CodePudding user response:
Maybe you can use this
function hasArrayNegativeValue(valueArray){
for(i=0;i < valueArray.length;i )
{
if(valueArray[i] < 0){
return 'Negative';
}
}
return null;
}
console.log(hasArrayNegativeValue([4, 5, 6, 7, 8]));
console.log(hasArrayNegativeValue([100, 200, 300, 400, 500]));
console.log(hasArrayNegativeValue([-1, 4, 7, 11]));
CodePudding user response:
You can use built in array method .some()
.
const hasNegative = [-1, 4, 7, 11].some(elem => elem < 0);
The result will be true
, because this array contains element which is less than 0.
const result = hasNegative ? 'Negative' : 'Positive';
You can also put this logic into function and return result instead of assigning it to variable.