我对JavaScript很陌生,但这是我到目前为止所做的。我正在尝试使用下划线来帮助在两批独特的偶数和奇数中将它打印到控制台上,我想我就像90%那样但是我碰到了墙。
var arr = ([1,3,5,2,0,4,5,2,9,9,8,2]);
sort(arr);
function sort(arr) {
var evens = [];
var odds = [];
for(var i = 0; i < arr.length; i++) {
if(arr[i] % 2 ){
odds.push(arr[i]);
} else if(!(arr[i] % 2)) {
evens.push(arr[i]);
}
}
console.log("ODD NUMBERS:" + " " + odds);
console.log("EVEN NUMBERS:" + " " + evens);
if(_.uniq(evens).length != evens.length || _.uniq(odds).length != odds.length){
console.log("FAIL!");
}
}
答案 0 :(得分:2)
首先,你需要过滤你的数组(偶数或奇数),然后应用_.uniq
var arr = [1,3,5,2,0,4,5,2,9,9,8,2];
var evens = _.filter(arr, function(num){ return num % 2 == 0; });
var odds = _.filter(arr, function(num){ return num % 2 != 0; });
console.log("EVEN NUMBERS: "+_.uniq(evens));
console.log("ODD NUMBERS: "+_.uniq(odds));
&#13;
<script src="http://underscorejs.org/underscore-min.js"></script>
&#13;
答案 1 :(得分:1)
arr[i] % 2
在0
条件下评估为false
或if
if (arr[i] % 2 === 0) {
// even
} else {
// not even
}
答案 2 :(得分:0)
不确定我的要求是否合适,但是这是你用ES6做的方法。
filter
method在大多数浏览器中得到广泛支持,并允许以更具说明性的方式剖析数组。
const arr = [1,3,5,2,0,4,5,2,9,9,8,2];
const isEven = el => el % 2 === 0;
const isOdd = el => el % 2 !== 0;
const evens = arr.filter(isEven);
const odds = arr.filter(isOdd);
console.log(`Unique evens: ${_.uniq(evens)}`); // => "Unique evens: 2,0,4,8"
console.log(`Unique odds: ${_.uniq(odds)}`); // "Unique odds: 1,3,5,9"
答案 3 :(得分:0)
第一个问题:ReferenceError: _ is not defined.
确保h <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
位于html文件中的某个位置,或者JS文件中需要另一种方式使用Underscore。
第二个问题:“我期待没有错误,并且两个列表都以唯一值打印到控制台。”
这种情况不会发生,因为您还没有在数组上调用uniq
函数。用_.uniq()
包裹两个数组,如下所示:
console.log("ODD NUMBERS:", _.uniq(odds));
console.log("EVEN NUMBERS:", _.uniq(evens));
或者,您可以在排序之前调用输入数组上的_.uniq
,从而在排序时节省处理时间。
无论哪种方式,假设定义了Underscore,您应该得到预期的结果。