如何拆分一组数字并将正数推送到数组而将负数推送到另一个? var myarr = [1,2,3,-1,5,-3];
答案 0 :(得分:3)
您可以将singn推送到对象的相应属性,其中值是数组。
var array = [1, 2, 3, -1, 5, -3],
positive = [],
negative = [],
hash = { 1: positive, '-1': negative };
array.forEach(a => hash[Math.sign(a)].push(a));
console.log(positive);
console.log(negative);

将零视为正数:
var array = [1, 2, 3, -1, 5, -3, 0],
positive = [],
negative = [],
hash = { true: positive, false: negative };
array.forEach(a => hash[a >= 0].push(a));
console.log(positive);
console.log(negative);

过滤的经典方式
var array = [1, 2, 3, -1, 5, -3, 0],
negative = [],
positive = array.filter(a => a >= 0 || (negative.push(a), false));
console.log(positive);
console.log(negative);

答案 1 :(得分:1)
试试这个:
var myarr = [ 1,2,3,-1.5,-3 ];
var positive = [];
var negative = [];
for( key in myarr ) {
var item = myarr[ key ];
if( item < 0 ) {
negative.push( item );
}
else {
positive.push( item );
}
}
答案 2 :(得分:0)
检查每个数组值是否小于0,如果小于0则检查不是否为负数,否则为正
试试这段代码
var myarr = [1, 2, 3, -1, 5, -3];
var pos = [];
var neg = [];
for (i = 0; i < myarr.length; i++) {
if (myarr[i] < 0) {
neg.push(myarr[i]);
} else {
pos.push(myarr[i]);
}
}
console.log(neg);
console.log(pos);
&#13;